// Routines to sort arrays of integers. // (c) 1997 duane a. bailey import structure.*; public class MergeSort { //+mergeSort public static void mergeSort(int data[], int n) // pre: 0 <= n <= data.length // post: values in data[0..n-1] are in ascending order { mergeSortRecursive(data,new int[n],0,n-1); } //-mergeSort //+mergeSortRecursive private static void mergeSortRecursive(int data[], int temp[], int low, int high) // pre: 0 <= low <= high < data.length // post: values in data[low..high] are in ascending order { int n = high-low+1; int middle = low + n/2; int i; if (n < 2) return; // move lower half of data in to temporary storage for (i = low; i < middle; i++) { temp[i] = data[i]; } // sort lower half of array mergeSortRecursive(temp,data,low,middle-1); // sort upper half of array mergeSortRecursive(data,temp,middle,high); // merge halves together merge(data,temp,low,middle,high); } //-mergeSortRecursive //+mergeOperation private static void merge(int data[], int temp[], int low, int middle, int high) // pre: data[middle..high] are ascending // temp[low..middle-1] are ascending // post: data[low..high] contains all values in ascending order { int ri = low; // result index int ti = low; // temp index int di = middle; // destination index // while two lists are not empty merge smaller value while (ti < middle && di <= high) { if (data[ti] < temp[di]) data[ri++] = data[di++]; else data[ri++] = temp[ti++]; } // possibly some values left in temp array while (ti < middle) { data[ri++] = temp[ti++]; } // ...or possibly some values left (in correct place) in data array } //-mergeOperation //+swap public static void swap(int data[], int i, int j) // pre: 0 <= i,j < data.length // post: data[i] and data[j] are exchanged { int temp; temp = data[i]; data[i] = data[j]; data[j] = temp; } //-swap //+vectorSort public static void swap(Vector data, int i, int j) // pre: 0 <= i,j < data.size() // post: i-th j-th elements of data are exchanged { Object temp; temp = data.elementAt(i); data.setElementAt(data.elementAt(j),i); data.setElementAt(temp,j); } //-vectorSort }