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

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

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

24条回答
  •  隐瞒了意图╮
    2020-11-28 01:11

    The accepted solution by sdcvvc in C++11.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    using std::vector;
    using std::cout;
    using std::endl;
    using std::random_shuffle;
    using std::min;
    using std::max;
    
    vector create_tournament(const vector& input) {
      // make sure we have at least two elements, so the problem is interesting
      if (input.size() <= 1) {
        return input;
      }
    
      vector 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& 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& v) {
      for (const auto& el : v) {
        cout << el << " ";
      }
      cout << endl;
    }
    
    int main() {
    
      vector 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;
    }
    

提交回复
热议问题