/** * A demo of selection sort. * @author Sean Barker */ public class SelectionSort { private static void swap(int[] data, int i, int j) { int temp = data[i]; data[i] = data[j]; data[j] = temp; } public static void selectionSort(int[] data) { for (int unsorted = data.length; unsorted > 0; unsorted--) { int largest = 0; // index of largest value this pass for (int i = 1; i < unsorted; i++) { if (data[largest] < data[i]) { largest = i; // found a new index of largest value } } swap(data, largest, unsorted - 1); // put the largest value into position } } public static void main(String[] args) { selectionSortDemo(10, 100); } /** * Runs a demo of selection sort (same algorithm as above, but uses the SortSim * class to display the steps of the sort). */ public static void selectionSortDemo(int dataSize, int maxVal) { SortSim s = new SortSim(dataSize, maxVal); int[] data = s.getData(); s.update(false, -1, -1, "starting selection sort"); for (int unsorted = data.length; unsorted > 0; unsorted--) { int largest = 0; // index of largest value this pass for (int i = 1; i < unsorted; i++) { if (data[largest] < data[i]) { largest = i; } s.update(false, largest, i, "best candidate is " + data[largest]); } swap(data, largest, unsorted - 1); s.update(true, largest, unsorted - 1, "sorted next-largest value " + data[unsorted - 1]); } s.finish(); } }