// APS101, Winter 2009: Lecture 34 (Apr. 2) // // Review: last time we developed two more sorting algorithms, insertion sort and selection sort, and compared them to the bubblesort algorithm we wrote previously. Sort.bubbleSort2(new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}) Sort.insertionSort(new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}) Sort.selectionSort(new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}) // is this the best way to compare sorting algorithms? // we want to know which algorithm is the FASTEST! // how do we measure time? (we can use the Date class) import java.util.Date; Date d1 = new Date(); // new object with the current time d1.getTime() // returns a number in milliseconds Date d2 = new Date(); d2.getTime() - d1.getTime() // time passed, in milliseconds // now, let's add a timer to Sort.java... Sort.bubbleSort2(new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}); Sort.insertionSort(new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}); Sort.selectionSort(new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 10, 4, 6, 44, 3, 123}); // in order to observe a difference in speed between the three algorithms, // we need to test them on LARGE arrays (with many elements). // we also need to test 3 different cases: 1) best case (array is already sorted) 2) intermediate case (elements are in random order) 3) worst case (elements are in descending order) // how do we produce an array with many elements, in random order? int[] array = new int[10000]; import java.util.Random; Random r = new Random(); for (int i = 0; i < 10000; i++) { array[i] = r.nextInt(); } Sort.selectionSort(array) Sort.insertionSort(array) // instead of running these experiments manually in the Interactions pane, // we will write a TimeSort utility class that measures sorting times // for random/sorted/reverse-sorted arrays of size N. // (see TimeSort.java) // we have a "main" method that runs everything automatically. // all you need to change is the size of the array. java TimeSort // exercise: try arrays of various sizes - 100, 1000, 10k, 25k, 50k, 75k, 100K, 250K, 500K, 1M, // and draw a time vs. size graph for each algorithm and array content (random, sorted, reversed). // what do you see? why does the number of comparisons and swaps sometimes become negative? how do you fix this?