// Helene Martin, CSE 143 // This program compares the runtime of the selection and merge sort algorithms. import java.util.*; // for Random /* Selection sort: 8000 elements => 110 ms 16000 elements => 386 ms 32000 elements => 1537 ms 64000 elements => 6261 ms 128000 elements => 24556 ms Merge sort: 128000 elements => 58 ms 256000 elements => 52 ms 512000 elements => 94 ms 1024000 elements => 204 ms 2048000 elements => 437 ms 4096000 elements => 884 ms */ public class Sorting { private static final Random RAND = new Random(); // random number generator public static void main(String[] args) { int length = 8000; // initial length of array to sort int runs = 10; // how many times to double length 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); // selectionSort(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) { // swap int temp = a[i]; 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) { // base case: lists of length 0 and 1 are already sorted! if (a.length > 1) { int[] left = Arrays.copyOfRange(a, 0, a.length / 2); int[] right = Arrays.copyOfRange(a, a.length / 2, a.length); mergeSort(left); mergeSort(right); merge(a, left, right); } } // Merges the contents of sorted lists left and right into result, // preserving sorted order. // pre: result.length = left.length + right.length; left is sorted; right is // sorted private static void merge(int[] result, int[] left, int[] right) { int leftIndex = 0; int rightIndex = 0; for (int i = 0; i < result.length; i++) { // be careful about the order of tests if (rightIndex >= right.length || (leftIndex < left.length && left[leftIndex] < right[rightIndex])) { result[i] = left[leftIndex]; leftIndex++; } else { result[i] = right[rightIndex]; rightIndex++; } } } // 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); } } } }