/** * A demo of insertion sort. * @author Sean Barker */ public class InsertionSort { public static void insertionSort(int[] data) { for (int numSorted = 1; numSorted < data.length; numSorted++) { // take the first unsorted value int toInsert = data[numSorted]; // find where it goes among the sorted int checkIndex = numSorted - 1; while (checkIndex >= 0 && toInsert < data[checkIndex]) { // make room for the new value data[checkIndex + 1] = data[checkIndex]; checkIndex--; } // reinsert value data[checkIndex + 1] = toInsert; } } public static void main(String[] args) { insertionSortDemo(10, 100); } /** * Runs a demo of insertion sort (same algorithm as above, but uses the SortSim * class to display the steps of the sort). */ public static void insertionSortDemo(int dataSize, int maxVal) { SortSim s = new SortSim(dataSize, maxVal); int[] data = s.getData(); s.update(false, -1, -1, "starting insertion sort"); for (int numSorted = 1; numSorted < data.length; numSorted++) { // take the first unsorted value int toInsert = data[numSorted]; s.update(false, numSorted, -1, "next value to insert is " + data[numSorted]); data[numSorted] = -1; // find where it goes among the sorted int checkIndex = numSorted - 1; s.update(false, numSorted, checkIndex + 1, "looking for insertion point for " + toInsert); while (checkIndex >= 0 && toInsert < data[checkIndex]) { // make room for the new value data[checkIndex + 1] = data[checkIndex]; data[checkIndex] = -1; s.update(false, checkIndex, -1, "looking for insertion point for " + toInsert); checkIndex--; } // reinsert value data[checkIndex + 1] = toInsert; s.update(true, -1, checkIndex + 1, "reinserted value " + toInsert); } s.finish(); } }