// Routines to sort arrays of integers. // (c) 1997 duane a. bailey import structure.*; public class InsertionSort { //+insertionSort public static void insertionSort(int data[], int n) // pre: 0 <= n <= data.length // post: values in data[0..n-1] are in ascending order { int numSorted = 0; // number of values in place int index; // general index while (numSorted < n) { // take the first unsorted value int temp = data[numSorted]; // ...and insert it among the sorted: for (index = numSorted; index > 0; index--) { if (temp < data[index-1]) { data[index] = data[index-1]; } else { break; } } // re-insert value data[index] = temp; numSorted++; } } //-insertionSort //+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 insertionSort(Vector data) // pre: 0 <= n <= data.size() // post: values in data are in ascending order { int n = data.size(); // vector size int numSorted = 0; // number of values in place int index; // general index while (numSorted < n) { // take the first unsorted value PhoneBook temp = (PhoneBook)data.elementAt(numSorted); // ...and insert it among the sorted: for (index = numSorted; index > 0; index--) { if (temp.lessThan((PhoneBook)data.elementAt(index-1))) { data.setElementAt(data.elementAt(index-1),index); } else { break; } } // re-insert value data.setElementAt(temp,index); numSorted++; } } 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 }