// CSE 373, Winter 2013 // This program compares the runtime of various sorting algorithms. // Today's version contains bogo and bubble sort. import java.util.*; // for Random public class Sorting { private static final Random RAND = new Random(42); // random number generator public static void main(String[] args) { int LENGTH = 100; // initial length of array to sort int RUNS = 15; // how many times to grow by 2? for (int i = 0; i < RUNS; i++) { int[] a = createAscendingArray(LENGTH); // perform a sort and time how long it takes long startTime1 = System.currentTimeMillis(); // bogoSort(a); bubbleSort(a); long endTime1 = System.currentTimeMillis(); if (!isSorted(a)) { throw new RuntimeException("we suck!"); } System.out.printf("%10d elements => %6d ms \n", LENGTH, endTime1 - startTime1); LENGTH *= 2; // double size of array for next time } } // Arranges the elements of the given array into sorted order // using the "bubble sort" algorithm. public static void bubbleSort(int[] a) { for (int pass = 0; pass < a.length; pass++) { // make a sweep boolean changed = false; for (int i = 0; i < a.length - 1 - pass; i++) { if (a[i] > a[i + 1]) { swap(a, i, i + 1); changed = true; } } if (!changed) { return; } } } // Arranges the elements of the given array into sorted order // using the "bogo sort" algorithm. public static void bogoSort(int[] a) { while (!isSorted(a)) { shuffle(a); } } // Swaps the values at the two given indexes in the given array. private static void swap(int[] a, int i, int j) { if (i != j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } // Randomly rearranges the elements of the given array. private static void shuffle(int[] a) { for (int i = 0; i < a.length; i++) { // move element i to a random index in [i .. length-1] int randomIndex = (int) (Math.random() * a.length - i); swap(a, i, i + randomIndex); } } // Returns true if the given array is in sorted ascending order. private static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } // 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; } // Creates an array of the given length, fills it with ordered // non-negative integers, and returns it. public static int[] createAscendingArray(int length) { int[] a = new int[length]; for (int i = 0; i < a.length; i++) { a[i] = i; } return a; } // Creates an array of the given length, fills it with reverse-ordered // non-negative integers, and returns it. public static int[] createDescendingArray(int length) { int[] a = new int[length]; for (int i = 0; i < a.length; i++) { a[i] = a.length - 1 - i; } return a; } }