How to find the majority element in int array with C#

1 Answer

0 votes
// A majority element = element that appears more than size/2 times in an array[size] 

using System;

class Program
{
    public static int getMajorityElement(int[] arr) {
		int[] num = new int[10];
		int len = arr.Length;

		for (int i = 0; i < len; i++) {
			num[arr[i]]++;
		}

		for (int i = 0; i < 9; i++) {
			if (num[i] != 0) {
				Console.WriteLine("{0:D} : {1:D}", i, num[i]);
				if (num[i] > len / 2) {
					return i;
				}
			}
		}

		return 0;
	}
	
    static void Main() {
        int[] arr = new int[] {2, 5, 3, 5, 5, 1, 5, 5, 5, 7, 3};

		int majority = getMajorityElement(arr);

		if (majority != 0) {
			 Console.WriteLine("majority element = {0:D}\n", majority);
		}
		else {
			 Console.WriteLine("Majority element doesn't exists\n");
		}
    }
}





/*
run:
 
1 : 1
2 : 1
3 : 2
5 : 6
majority element = 5
 
*/

 



answered Apr 21, 2023 by avibootz
edited Apr 21, 2023 by avibootz

Related questions

1 answer 113 views
1 answer 116 views
1 answer 123 views
1 answer 104 views
1 answer 118 views
1 answer 115 views
1 answer 155 views
...