Find the 2nd largest element in an array with minimum number of comparisons

后端 未结 24 1346
清酒与你
清酒与你 2020-11-28 01:03

For an array of size N, what is the number of comparisons required?

24条回答
  •  悲哀的现实
    2020-11-28 01:20

    case 1-->9 8 7 6 5 4 3 2 1
    case 2--> 50 10 8 25 ........
    case 3--> 50 50 10 8 25.........
    case 4--> 50 50 10 8 50 25.......

    public void second element()  
    {
          int a[10],i,max1,max2;  
          max1=a[0],max2=a[1];  
          for(i=1;imax1)  
              {
                 max2=max1;  
                 max1=a[i];  
              }  
             else if(a[i]>max2 &&a[i]!=max1)  
               max2=a[i];  
             else if(max1==max2)  
               max2=a[i];  
          }  
    }
    

提交回复
热议问题