Function to find second largest element of array

Some interviewers ask the question - write a program to find second largest/smallest element of the array. Then they add do it in single iteration.

No need to fret.

  • Initialize largest with 0th element of the array
  • Iterate over 1st element to nth element
    • If array element is >largest
      • set second_largest to largest
      • set largest to array element

But the question is what do we initialize the second largest element to. We know from experience that 0 is not the solution. Because some or all elements could be negative.

So let us initialize largest with 0th element of the array and also second largest with 0th element of the array.

So here is our code
 int second_largest(int *arr,int n)  
 {  
   int lar,sec_lar=0;int i;  
   lar = sec_lar= arr[0];arr++;  
   for(i=1;i<n;i++,arr++)  
   {  
    if(*arr>lar)  
    {  
      sec_lar = lar;  
      lar = *arr;  
    }   
    else if(*arr>sec_lar)  
    {  
      sec_lar = *arr;  
    }  
    else if(lar==sec_lar )  
    {  
      sec_lar =*arr;  
     }  
   }  
   return sec_lar;  
 }   

Note : We have used the last condition because, initially largest = second laregst = 0th element

Comments

Popular Posts