Saturday, June 12, 2010

Second Smallest and Second Largest in an array


using System;


using System.Collections.Generic;


using System.Text;


using System.Collections;


 


namespace ConsoleApplication1


{


    class Program


    {


        static void Main(string[] args)


        {


            int[] arr = {1,2,3,4,5,6,7,8,9,10};


            int smallest, secsmallest, largest, seclargest;


            //Take the first two elements as largest and secondlargest according to the following conditions.


            if (arr[0] < arr[1])


            {


                smallest = arr[0];


                secsmallest = arr[1];


                largest = arr[1];


                seclargest = arr[0];


            }


            else


            {


                smallest = arr[1];


                secsmallest = arr[0];


                largest = arr[0];


                seclargest = arr[1];


            }


            for (int i = 2; i < arr.Length; i++)


            {


                if (arr[i] < smallest || arr[i] > largest)


                {


                    //Element is smaller than smallest, smallest becomes secondsmallest.


                    if (arr[i] < smallest)


                    {


                        secsmallest = smallest;


                        smallest = arr[i];


                    }


                    //Element is larger than largest, largest becomes secondlargest.


                    else


                    {


                        seclargest = largest;


                        largest = arr[i];


                    }


                }


                else if ((arr[i]>smallest && arr[i]<secsmallest) ||     


                         (arr[i]<largest && arr[i]>seclargest))


                {


                    //Element lies between the largest and secondlargest, secondlargest assigned element.


                    if (arr[i] > smallest && arr[i] < secsmallest)


                    { secsmallest = arr[i]; }


                    else


                    { seclargest = arr[i]; }


                }


            }


            Console.WriteLine("Second smallest: " + secsmallest);


            Console.WriteLine("Second largst: " + seclargest);


        }


    }

}

No comments:

Post a Comment