// CSE 143, Winter 2012 // This program compares the runtime of the selection and merge sort algorithms. import java.util.*; // for Random /* Selection sort: 8000 elements => 146 ms 16000 elements => 576 ms 32000 elements => 2226 ms 64000 elements => 8434 ms 128000 elements => 34475 ms Merge sort: 1024000 elements => 392 ms 2048000 elements => 854 ms 4096000 elements => 1868 ms 8192000 elements => 4204 ms */ public class Sorting { private static final Random RAND = new Random(); // random number generator public static void main(String[] args) { int LENGTH = 32000; // initial length of array to sort int RUNS = 10; // how many times to grow by 2? for (int i = 0; i < RUNS; i++) { int[] a = createRandomArray(LENGTH); // perform a sort and time how long it takes long startTime = System.currentTimeMillis(); mergeSort(a); long endTime = System.currentTimeMillis(); ensureSorted(a); System.out.printf("%10d elements => %6d ms \n", LENGTH, endTime - startTime); LENGTH *= 2; // double size of array for next time } } // Rearranges the elements of a into sorted order using // the selection sort algorithm. public static void selectionSort(int[] a) { for (int i = 0; i < a.length - 1; i++) { // look for smallest element int minIndex = i; for (int j = i + 1; j < a.length; j++) { if (a[j] < a[minIndex]) { minIndex = j; } } if (minIndex != i) { int temp = a[i]; // swap a[i] = a[minIndex]; a[minIndex] = temp; } } } // Rearranges the elements of a into sorted order using the // merge sort algorithm. public static void mergeSort(int[] a) { if (a.length > 1) { // split the array int[] left = Arrays.copyOfRange(a, 0, a.length / 2); int[] right = Arrays.copyOfRange(a, a.length / 2, a.length); // sort the halves mergeSort(left); mergeSort(right); // merge the halves merge(a, left, right); } } private static void merge(int[] a, int[] left, int[] right) { int i1 = 0; // left int i2 = 0; // right for (int i = 0; i < a.length; i++) { // compare left/right element; pick smaller one if (i2 >= right.length ||(i1 < left.length && left[i1] < right[i2])) { a[i] = left[i1]; i1++; } else { a[i] = right[i2]; i2++; } } } // Creates an array of the given length, fills it with random // non-negative integers, and returns it. public static int[] createRandomArray(int length) { int[] a = new int[length]; for (int i = 0; i < a.length; i++) { a[i] = RAND.nextInt(1000000000); } return a; } // Checks whether the given array is in sorted order. // Throws an IllegalStateException if it is not. public static void ensureSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { throw new IllegalStateException("array not sorted at index " + i); } } } }