Tuesday, August 23, 2011

C# code to find second largest Element in an array

Question : Write C# code to find second largset element in an Integer Array
Possible solutions
1. Store values in List and sort the list and find the 3rd element in the list
2.Use Hashtable
3.Use for loop
4.Use bubble sort or any other sorting algorithm and print 3rd element (Code snippet will be published later)

Use for loop
private static void getSecondLargest(int[] intArray)
        {
            int maxVal = 0;
            int secondMax = 0;

            for (int i = 0; i < intArray.Length; i++)
            {
                if (intArray[i] > maxVal)
                {
                    secondMax = maxVal;
                    maxVal = intArray[i];
                }
                else if (intArray[i] > secondMax)
                {
                    // Print Second Largest Value
                    secondMax = intArray[i];
                }
            }
            Console.WriteLine("Second Largest Value : "+secondMax);
        }


No comments:

Post a Comment