University of Toronto - Fall 2000
Department of Computer Science

Week 13 - Sorting

Counting Sort

public static void sort (int[] list) { int[] sorted = new int[list.length]; for (int i = 0; i < list.length; i++) { int smallerCount = countSmaller (list[i], list); sorted[smallerCount] = list[i]; } for (int i = 0; i < list.length; i++) { list[i] = sorted[i]; } } // This version doesn't use the countSmaller method. public static void sort (int[] list) { (a) int[] sorted = new int[list.length]; (a) for (int i = 0; i < list.length; i++) { int smallerCount = 0; for (int j = 0; j < list.length; j++) { if (list[j] < list[i]) { //comp (b) smallerCount++; } } sorted[smallerCount] = list[i]; //move } for (int i = 0; i < list.length; i++) { list[i] = sorted[i]; //move } }

Insertion Sort

// sort: insertion sort works by inserting each value // into a previously sorted subset of the list. public static void sort (int[] list) { for (int i=1; i < list.length; i++) { int key = list[i]; int pos = i; // shift larger values to the right while(pos>0 && list[pos-1] > key) { list[pos] = list [pos-1]; pos--; } list[pos] = key; } }

Selection Sort

// sort: selection sort works by putting each value // into its final position, one at a time. public static void sort (int[] list) { for (int i=0; i < list.length - 1; i++) { int min = i; // position of smallest element for (int scan=i+1; scan < list.length; scan++) { if (list[scan] < list[min]) min = scan; } // Swap int temp = list[min]; list[min] = list[i]; list[i] = temp; } }

Bubble Sort

// sort: same description as before, as far as the // user is concerned, but the insides are different! public static void sort (int[] list) { final int N = list.length; // N - 1 scans for (int scan = 0; scan < N - 1; scan++) { // Loop for each pair to be swapped (lower // is the index of lower pair to be swapped). for (int lower=0; lower<N-1-scan; lower++) { // If out of order, swap the pair. if (list[lower] > list[lower+1]) { int temp = list[lower]; list[lower] = list[lower + 1]; list[lower + 1] = temp; } } } }