java - How do I make this merge sort go in descending order rather than ascending? -
this simple problem. can't figure out how make sort in descending order rather ascending. can me out?
public static void sortyear(movie4[] movies, int low, int high) { if ( low == high ) return; int mid = ( low + high ) / 2; sortyear( movies, low, mid ); sortyear( movies, mid + 1, high ); mergeyears(movies, low, mid, high ); } public static void mergeyears(movie4[] movies, int low, int mid, int high) { movie4[] temp = new movie4[ high - low + 1 ]; int = low, j = mid + 1, n = 0; while ( <= mid || j <= high ) { if ( > mid ) { temp[ n ] = movies[ j ]; j++; } else if ( j > high ) { temp[ n ] = movies[ ]; i++; } else if ( movies[ ].getyear() < movies[ j ].getyear()) { temp[n] = movies[i]; i++; } else { temp[n] = movies[j]; j++; } n++; } ( int k = low ; k <= high ; k++ ) { movies[ k ] = temp[ k - low ]; } }
in attempt answer question yourself, i'll add comments code.
all of real work in mergeyears:
public static void mergeyears(movie4[] movies, int low, int mid, int high) { movie4[] temp = new movie4[ high - low + 1 ]; // 'i' tracks index head of low half of range. // 'j' tracks index head of upper half of range. int = low, j = mid + 1, n = 0; // while still have entry in 1 of halves. while ( <= mid || j <= high ) { // lower half exhausted. copy upper half. if ( > mid ) { temp[ n ] = movies[ j ]; j++; } // upper half exhausted. copy lower half. else if ( j > high ) { temp[ n ] = movies[ ]; i++; } // compare 2 movie4 objects @ head of lower , upper halves. // if lower less upper copy lower. else if ( movies[ ].getyear() < movies[ j ].getyear()) { temp[n] = movies[i]; i++; } // lower is greater upper. copy upper. else { temp[n] = movies[j]; j++; } n++; } // copy temp buffer 'movie' array. ( int k = low ; k <= high ; k++ ) { movies[ k ] = temp[ k - low ]; } }
Comments
Post a Comment