Tech Point Fundamentals

Thursday, January 27, 2022

C# Program to Find the Majority Array Element

C# Program to Find the Majority Array Element


Most of the IT companies check the coding skills and problem-solving skills as well along with the theoretical interview questions. Sometimes you are free to write the pseudo code and sometimes you are asked to write the complete program either on any paper or any editor. 

This question is asked in the coding interview to write the program. Here you can find the program as well as a live running program so that you can test the program immediately.

Watch our videos here


How can you find the majority element in an unsorted array? Write a program to find the majority element in an array.

C# Program to Find the Majority Array Element


// Author 	: Tech Point Fundamentals
// Website 	:
// Channel	:
// Demo		: Majority Array Element

using System;
using System.Collections.Generic;

public class Program
public static void Main()
	int[] unsortedArray = new int[10] {3, 3, 6, 3, 1, 3, 8, 3, 7, 3};			
	Console.WriteLine("Input UnSorted Array: ");	
	Console.WriteLine("------------------------------------------------ ");	
	for( int i = 0; i < unsortedArray.Length; i++)
	// Majority Array Element
	var majorityElement = MajorityElement(unsortedArray);
	Console.WriteLine("\nMajority Array Element: " + majorityElement);	
 public static int MajorityElement(int[] array)
	 Dictionary<int, int> dictionary = new Dictionary<int, int>();
	 int majority = array.Length / 2;
	 foreach (int i in array)
		 if (dictionary.ContainsKey(i))
			 if (dictionary[i] > majority)
				 return i;
			dictionary.Add(i, 1);		 
	 throw new Exception("No Majority Element Found in the Array");


                Input UnSorted Array: ------------------------------------------------ 3 3 6 3 1 3 8 3 7 3 Majority Array Element: 3

Live Demo

1 comment:

Please do not enter any HTML. JavaScript or spam link in the comment box.