Friday, July 12, 2013

Algorithm: Find second highest number from Array


 static void Main(string[] args)
        {
            int[] array = new int[] { 0, 6, 2, 7, 2, 6 };
            int first = int.MinValue;
            int second = int.MinValue;

            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] > first)
                {
                    second = first;
                    first = array[i];                  
                }
                else if (array[i] < first && array[i] > second)
                {
                    second = array[i];
                }
            }          

            Console.WriteLine(second);
            Console.ReadKey();
        }

Output:
6

Algorithm : Removing duplicates from array without using any other array or list.


static void Main(string[] args)
        {
            int[] array = new int[] { 0, 1, 2, 2, 5 };
            int numDups = 0;
            int temp = 0;
            for (int i = 0; i < array.Length; i++)
            {

                for (int j = 0; j < i; j++)
                {
                    if (array[i] == array[j])
                    {
                        array[i] = int.MaxValue;
                        temp++;
                        break;
                    }
                }
            }

            // Sort array so that we can resize and decard extra elements.
            for (int i = 0; i < array.Length; i++)
            {
                for (int j = i; j < array.Length; j++)
                {
                    if (array[i] >= array[j])
                    {
                        numDups = array[i];
                        array[i] = array[j];
                        array[j] = numDups;
                    }
                }
            }

            Array.Resize(ref array, array.Length - temp);

            Console.WriteLine(string.Concat(array));
            Console.ReadKey();
        }

Output:
0125

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