// Routines to sort arrays // (c) 1997 duane a. bailey // modified to sort Vectors of Associations by allen tucker 9/21/97 import structure.*; public class VectorMergeSort { //+mergeSort public static void mergeSort(Vector data, int n) // pre: 0 <= n <= data.length // post: values in data[0..n-1] are in ascending order { mergeSortRecursive(data, new Vector(n), 0, n-1); } //-mergeSort //+mergeSortRecursive private static void mergeSortRecursive(Vector data, Vector 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.setElementAt(data.elementAt(i), 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(Vector data, Vector 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) { // here, we're assuming a vector of integers, so we can compare two of them if (((ComparableInt)temp.elementAt(ti)).lessThan (((ComparableInt)data.elementAt(di)))) { data.setElementAt(temp.elementAt(ti), ri); ri++; ti++; } else { data.setElementAt(data.elementAt(di), ri); ri++; di++; } } // possibly some values left in temp array while (ti < middle) { data.setElementAt(temp.elementAt(ti), ri); ri++; ti++; } // ...or possibly some values left (in correct place) in data array } //-mergeOperation }