Find majority element in an unsorted array in C#

 

Find majority element in an unsorted array


In this article we will see how to find the majority of an element in an unsorted array.


C# code

static void findMajorityElement()

        {

            int[] arr = { 1, 2, 3, 4, 5, 2, 2, 2, 2 };

            int length = arr.Length;

 

            int maxCount = 0;

            int index = -1;

            for (int i = 0; i < length; i++)

            {

                int count = 0;

                for (int j = 0; j < length; j++)

                {

                    if (arr[i] == arr[j])

                        count++;

                }

 

                // update maxCount if count of

                // current element is greater

                if (count > maxCount)

                {

                    maxCount = count;

                    index = i;

                }

            }

 

            // if maxCount is greater than n/2

            // return the corresponding element

            if (maxCount > length / 2)

                Console.WriteLine("Majority Element is :- " + arr[index]);

 

            else

                Console.WriteLine("No Majority Element");

        }


Output



Share this

Related Posts

Previous
Next Post »