C# program to find majority element in an unsorted array
To find the majority element in an unsorted array using C#, you can use the dictionary object which will count the how many times value of the array idex is repeated. Here's an example program that finds the majority element in an unsorted array:
using System;
public class Program {
public static void Main(string[] args)
{
int[] numbers = { 2, 4, 3, 4, 4, 2, 14, 14, 6, 14, 14, 9, 9 };
int majorityElement = FindMajorityElement(numbers);
if (majorityElement != -1)
{
Console.WriteLine("The majority element is: " + majorityElement);
}
else
{
Console.WriteLine("No majority element found.");
}
Console.ReadKey();
}
public static int FindMajorityElement(int[] nums)
{
Dictionary keyValuePairs= new Dictionary();
foreach (int num in nums)
{
if (!keyValuePairs.ContainsKey(num))
keyValuePairs.Add(num, 1);
else if (keyValuePairs.ContainsKey(num))
{
keyValuePairs[num] = keyValuePairs[num] + 1;
}
}
int value = 0, key1 =0;
foreach(int key in keyValuePairs.Keys)
{
if (keyValuePairs[key] > value)
{
value = keyValuePairs[key];
key1 = key;
}
}
return key1;
}
}
Below is the output of the above program: