// Allison Obourn // CSE 143 - Lecture 16 // This program compares the runtime of the selection and // merge sort algorithms. import java.util.*; // for Random /* Selection sort 8000 elements => 268 ms 16000 elements => 884 ms 32000 elements => 2112 ms 64000 elements => 8551 ms 128000 elements => 33778 ms 256000 elements => 134732 ms Merge sort 8000 elements => 63 ms 16000 elements => 47 ms 32000 elements => 47 ms 64000 elements => 46 ms 128000 elements => 94 ms 256000 elements => 172 ms 512000 elements => 390 ms 1024000 elements => 797 ms 2048000 elements => 1665 ms 4096000 elements => 3396 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(); // selectionSort(a); mergeSort(a); // Arrays.toString(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) { if(a.length >= 2) { 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 i1 = 0; int i2 = 0; for(int i = 0; i < result.length; i++) { if(i2 >= right.length || (i1 < left.length && left[i1] < right[i2])) { result[i] = left[i1]; i1++; } else { result[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); } } } }