Advertisement
Taraxacum

Find Max and Min

Nov 19th, 2018
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <ctime>
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. template <class T>
  8. struct MaxMin {
  9.     T *max, *min;
  10. };
  11.  
  12. template <class T>
  13. MaxMin<T> findMaxMin(T* lh, T* rh)
  14. {
  15.     if (lh == rh) {
  16.         return { lh, rh };
  17.     }
  18.  
  19.     T* mid = lh + (rh - lh) / 2;
  20.     MaxMin<T> mml = findMaxMin(lh, mid);
  21.     MaxMin<T> mmr = findMaxMin(mid + 1, rh);
  22.  
  23.     return {
  24.         (*(mml.max) < *(mmr.max) ? mmr.max : mml.max),
  25.         (*(mml.min) > *(mmr.min) ? mmr.min : mml.min)
  26.     };
  27. }
  28.  
  29. int main()
  30. {
  31.     srand(time(NULL));
  32.     int arr[10] = { 0 };
  33.  
  34.     for (int i = 0; i < 10; i++) {
  35.         arr[i] = rand() % 100;
  36.         cout << arr[i] << " ";
  37.     }
  38.  
  39.     cout << endl;
  40.  
  41.     MaxMin<int> res = findMaxMin(arr, arr + 9);
  42.     cout << "max: " << *(res.max) << endl;
  43.     cout << "min: " << *(res.min) << endl;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement