fueanta

MaxMin for Large Arrays.

Feb 19th, 2017
155
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 3n/2 MaxMin
  2.  
  3. struct MinMax{
  4.    int Min,Max;
  5. }
  6.  
  7. MinMax FindMinMax(int[] array, int start, int end) {
  8.    MinMax  min_max;
  9.    int index;
  10.    int n = end - start + 1;//n: the number of elements to be sorted, assuming n>0
  11.    if ( n%2 != 0 ){// if n is odd
  12.  
  13.      min_max.Min = array[start];
  14.      min_max.Max = array[start];
  15.  
  16.      index = start + 1;
  17.    }
  18.    else{// n is even
  19.      if ( array[start] < array[start+1] ){
  20.        min_max.Min = array[start];
  21.        min_max.Max = array[start+1];
  22.  
  23.        index = start + 2;
  24.    }
  25.  
  26.    int big, small;
  27.    for ( int i = index; i < n-1; i = i+2 ){
  28.       if ( array[i] < array[i+1] ){ //one comparison
  29.         small = array[i];
  30.         big = array[i+1];
  31.       }
  32.       else{
  33.         small = array[i+1];
  34.         big = array[i];
  35.       }
  36.       if ( min_max.Min > small ){ //one comparison
  37.         min_max.Min = small;
  38.       }
  39.       if ( min_max.Max < big ){ //one comparison
  40.         min_max.Max = big;
  41.       }
  42.    }
  43.  
  44.    return min_max;
  45. }
RAW Paste Data