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

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

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

相关标签:
24条回答
  • 2020-11-28 01:10

    Use Bubble sort or Selection sort algorithm which sorts the array in descending order. Don't sort the array completely. Just two passes. First pass gives the largest element and second pass will give you the second largest element.

    No. of comparisons for first pass: n-1

    No. of comparisons for first pass: n-2

    Total no. of comparison for finding second largest: 2n-3

    May be you can generalize this algorithm. If you need the 3rd largest then you make 3 passes.

    By above strategy you don't need any temporary variables as Bubble sort and Selection sort are in place sorting algorithms.

    0 讨论(0)
  • 2020-11-28 01:10

    PHP version of the Gumbo algorithm: http://sandbox.onlinephpfunctions.com/code/51e1b05dac2e648fd13e0b60f44a2abe1e4a8689

    $numbers = [10, 9, 2, 3, 4, 5, 6, 7];
    
    $largest = $numbers[0];
    $secondLargest = null;
    for ($i=1; $i < count($numbers); $i++) {
        $number = $numbers[$i];
        if ($number > $largest) {
            $secondLargest = $largest;
            $largest = $number;
        } else if ($number > $secondLargest) {
            $secondLargest = $number;
        }
    }
    
    echo "largest=$largest, secondLargest=$secondLargest";
    
    0 讨论(0)
  • 2020-11-28 01:11

    The accepted solution by sdcvvc in C++11.

    #include <algorithm>
    #include <iostream>
    #include <vector>
    #include <cassert>
    #include <climits>
    
    using std::vector;
    using std::cout;
    using std::endl;
    using std::random_shuffle;
    using std::min;
    using std::max;
    
    vector<int> create_tournament(const vector<int>& input) {
      // make sure we have at least two elements, so the problem is interesting
      if (input.size() <= 1) {
        return input;
      }
    
      vector<int> result(2 * input.size() - 1, -1);
    
      int i = 0;
      for (const auto& el : input) {
        result[input.size() - 1 + i] = el;
        ++i;
      }
    
      for (uint j = input.size() / 2; j > 0; j >>= 1) {
        for (uint k = 0; k < 2 * j; k += 2) {
          result[j - 1 + k / 2] = min(result[2 * j - 1 + k], result[2 * j + k]);
        }
      }
    
      return result;
    }
    
    int second_smaller(const vector<int>& tournament) {
      const auto& minimum = tournament[0];
      int second = INT_MAX;
    
      for (uint j = 0; j < tournament.size() / 2; ) {
        if (tournament[2 * j + 1] == minimum) {
          second = min(second, tournament[2 * j + 2]);
          j = 2 * j + 1;
        }
        else {
          second = min(second, tournament[2 * j + 1]);
          j = 2 * j + 2;
        }
      }
    
      return second;
    }
    
    void print_vector(const vector<int>& v) {
      for (const auto& el : v) {
        cout << el << " ";
      }
      cout << endl;
    }
    
    int main() {
    
      vector<int> a;
      for (int i = 1; i <= 2048; ++i)
        a.push_back(i);
    
      for (int i = 0; i < 1000; i++) {
        random_shuffle(a.begin(), a.end());
        const auto& v = create_tournament(a);
        assert (second_smaller(v) == 2);
      }
    
      return 0;
    }
    
    0 讨论(0)
  • 2020-11-28 01:13

    Here is some code that might not be optimal but at least actually finds the 2nd largest element:

    if( val[ 0 ] > val[ 1 ] )
    {
        largest = val[ 0 ]
        secondLargest = val[ 1 ];
    }
    else
    {
        largest = val[ 1 ]
        secondLargest = val[ 0 ];
    }
    
    for( i = 2; i < N; ++i )
    {
        if( val[ i ] > secondLargest )
        {
            if( val[ i ] > largest )
            {
                secondLargest = largest;
                largest = val[ i ];
            }
            else
            {
                secondLargest = val[ i ];
            }
        }
    }
    

    It needs at least N-1 comparisons if the largest 2 elements are at the beginning of the array and at most 2N-3 in the worst case (one of the first 2 elements is the smallest in the array).

    0 讨论(0)
  • 2020-11-28 01:16
    #include<stdio.h>
    main()
    {
            int a[5] = {55,11,66,77,72};
            int max,min,i;
            int smax,smin;
            max = min = a[0];
            smax = smin = a[0];
            for(i=0;i<=4;i++)
            {
                    if(a[i]>max)
                    {
                            smax = max;
                            max = a[i];
                    }
                    if(max>a[i]&&smax<a[i])
                    {
                            smax = a[i];
                    }
            }
            printf("the first max element z %d\n",max);
            printf("the second max element z %d\n",smax);
    }
    
    0 讨论(0)
  • 2020-11-28 01:16

    Sort the array into ascending order then assign a variable to the (n-1)th term.

    0 讨论(0)
提交回复
热议问题