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

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

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

24条回答
  •  不知归路
    2020-11-28 01:27

    try this.

    max1 = a[0].
    max2.
    for i = 0, until length:
      if a[i] > max:
         max2 = max1.
         max1 = a[i].
         #end IF
      #end FOR
    return min2.
    

    it should work like a charm. low in complexity.

    here is a java code.

    int secondlLargestValue(int[] secondMax){
    int max1 = secondMax[0]; // assign the first element of the array, no matter what, sorted or not.
    int max2 = 0; // anything really work, but zero is just fundamental.
       for(int n = 0; n < secondMax.length; n++){ // start at zero, end when larger than length, grow by 1. 
            if(secondMax[n] > max1){ // nth element of the array is larger than max1, if so.
               max2 = max1; // largest in now second largest,
               max1 = secondMax[n]; // and this nth element is now max.
            }//end IF
        }//end FOR
        return max2;
    }//end secondLargestValue()
    

提交回复
热议问题