Friday, July 12, 2013

Algorithm: Finding highest number of occurrence of the value in array. If that number's occurrence is more then 50%



static void Main(string[] args)
        {
            int[] array = new int[] { 2, 1, 2, 2, 5 };            
            int count = 1; 
            int winner = array[0];            
            for (int i = 1; i < array.Length; i++)
            {
                if (array[i] == winner)
                {
                    count++;
                }
                else
                {
                    count--;
                }

                if (count == 0)
                {
                    winner = array[i];
                    count = 1;
                }
            }

            Console.WriteLine("Winner:" + winner);
            Console.ReadKey();


Output: Winner: 2 

No comments:

Post a Comment