// CSE 143, Winter 2011, Marty Stepp // This program compares the runtime of the selection and merge sort algorithms. import java.util.*; // for Random /* selection merge n time time 10000 540 20000 901 40000 3715 80000 14500 50 160000 90 ... 1280000 941 */ public class Sorting { private static final Random RAND = new Random(); // random number generator private static final int LENGTH = 1280000; // length of array to sort public static void main(String[] args) { System.out.println("Creating the array...\n"); int[] a = createArray(LENGTH); System.out.println("Performing sort...\n"); long startTime = System.currentTimeMillis(); // perform a sort and time how long it takes mergeSort(a); // Arrays.sort(a); long endTime = System.currentTimeMillis(); long elapsedTime = endTime - startTime; ensureSorted(a); System.out.println(elapsedTime + " ms to sort " + LENGTH + " elements"); } // Rearranges the elements of a into sorted order using the // merge sort algorithm. public static void mergeSort(int[] a) { if (a.length >= 2) { // divide list into halves int[] left = Arrays.copyOfRange(a, 0, a.length / 2); int[] right = Arrays.copyOfRange(a, a.length / 2, a.length); // sort each half mergeSort(left); mergeSort(right); // merge the sorted halves into a sorted whole merge(a, left, right); } } // Puts the contents of both sorted arrays 'left' and 'right' into the // given result array such that 'result' is in sorted order as well. public static void merge(int[] result, int[] left, int[] right) { // merge the two sorted halves into a sorted whole int i1 = 0; // index in left array int i2 = 0; // index in right array for (int i = 0; i < result.length; i++) { // compare left/right element; pick smaller one if (i2 >= right.length || (i1 < left.length && left[i1] < right[i2])) { result[i] = left[i1]; i1++; } else { result[i] = right[i2]; i2++; } } } // 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; } } swap(a, minIndex, i); } } // Swaps a[i] with a[j]. public static void swap(int[] a, int i, int j) { if (i != j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } // Creates an array of the given length, fills it with random data, // and returns it. public static int[] createArray(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); } } } }