21Elementarysorts-2X2.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
Algorithms ROBERT SEDGEWICK | KEVIN WAYNE 2.1 ELEMENTARY SORTS 2.1 ELEMENTARY SORTS ‣ rules of the game ‣ rules of the game ‣ selection sort ‣ selection sort Algorithms ‣ insertion sort Algorithms ‣ insertion sort FOURTH EDITION ‣ shellsort ‣ shellsort ‣ shuffling ‣ shuffling ROBERT SEDGEWICK | KEVIN WAYNE ROBERT SEDGEWICK | KEVIN WAYNE http://algs4.cs.princeton.edu ‣ convex hull http://algs4.cs.princeton.edu ‣ convex hull Sorting problem Sample sort client 1 Ex. Student records in a university. Goal. Sort any type of data. Chen 3 A 991-878-4944 308 Blair Ex 1. Sort random real numbers in ascending order. Rohde 2 A 232-343-5555 343 Forbes seems artificial, but stay tuned for an application Gazsi 4 B 766-093-9873 101 Brown item Furia 1 A 766-093-9873 101 Brown Kanaga 3 B 898-122-9643 22 Brown public class Experiment % java Experiment 10 Andrews 3 A 664-480-0023 097 Little { 0.08614716385210452 0.09054270895414829 key Battle 4 C 874-088-1212 121 Whitman public static void main(String[] args) { 0.10708746304898642 int N = Integer.parseInt(args[0]); 0.21166190071646818 Double[] a = new Double[N]; 0.363292849257276 Sort. Rearrange array of N items into ascending order. for (int i = 0; i < N; i++) 0.460954145685913 a[i] = StdRandom.uniform(); 0.5340026311350087 Andrews 3 A 664-480-0023 097 Little Insertion.sort(a); 0.7216129793703496 Battle 4 C 874-088-1212 121 Whitman for (int i = 0; i < N; i++) 0.9003500354411443 Chen 3 A 991-878-4944 308 Blair StdOut.println(a[i]); 0.9293994908845686 Furia 1 A 766-093-9873 101 Brown } Gazsi 4 B 766-093-9873 101 Brown } Kanaga 3 B 898-122-9643 22 Brown Rohde 2 A 232-343-5555 343 Forbes 3 4 Sample sort client 2 Sample sort client 3 Goal. Sort any type of data. Goal. Sort any type of data. Ex 2. Sort strings from file in alphabetical order. Ex 3. Sort the files in a given directory by filename. public class StringSorter { import java.io.File; % java FileSorter . public static void main(String[] args) public class FileSorter Insertion.class { { Insertion.java String[] a = In.readStrings(args[0]); public static void main(String[] args) InsertionX.class Insertion.sort(a); { InsertionX.java for (int i = 0; i < a.length; i++) File directory = new File(args[0]); Selection.class StdOut.println(a[i]); File[] files = directory.listFiles(); Selection.java } Insertion.sort(files); Shell.class } for (int i = 0; i < files.length; i++) Shell.java % more words3.txt StdOut.println(files[i].getName()); ShellX.class bed bug dad yet zoo ... all bad yes } ShellX.java } % java StringSorter words3.txt all bad bed bug dad ... yes yet zoo 5 6 Callbacks Callbacks: roadmap Goal. Sort any type of data. client object implementation import java.io.File; public class File public class FileSorter implements Comparable<File> { { sort() Double String Q. How can know how to compare data of type , , and public static void main(String[] args) ... java.io.File without any information about the type of an item's key? { public int compareTo(File b) File directory = new File(args[0]); { File[] files = directory.listFiles(); ... Insertion.sort(files); return -1; Callback = reference to executable code. for (int i = 0; i < files.length; i++) ... StdOut.println(files[i].getName()); return +1; ・Client passes array of objects to sort() function. } ... The sort() function calls back object's compareTo() method as needed. } return 0; ・ } } Implementing callbacks. ・Java: interfaces. Comparable interface (built in to Java) sort implementation public static void sort(Comparable[] a) C: function pointers. public interface Comparable<Item> ・ { { int N = a.length; ・C++: class-type functors. public int compareTo(Item that); for (int i = 0; i < N; i++) } ・C#: delegates. for (int j = i; j > 0; j--) if (a[j].compareTo(a[j-1]) < 0) ・Python, Perl, ML, Javascript: first-class functions. exch(a, j, j-1); key point: no dependence else break; on File data type } 7 8 Total order Comparable API A total order is a binary relation ≤ that satisfies: Implement compareTo() so that v.compareTo(w) ・Antisymmetry: if v ≤ w and w ≤ v, then v = w. ・Is a total order. ・Transitivity: if v ≤ w and w ≤ x, then v ≤ x. ・Returns a negative integer, zero, or positive integer ・Totality: either v ≤ w or w ≤ v or both. if v is less than, equal to, or greater than w, respectively. ・Throws an exception if incompatible types (or either is null). Ex. ・Standard order for natural and real numbers. ・Chronological order for dates or times. v w v w ・Alphabetical order for strings. w v … ・ less than (return -1) equal to (return 0) greater than (return +1) violates totality: (Double.NaN <= Double.NaN) is false an intransitive relation Built-in comparable types. Integer, Double, String, Date, File, ... Surprising but true. The <= operator for double is not a total order. (!) User-defined comparable types. Implement the Comparable interface. 9 10 Implementing the Comparable interface Two useful sorting abstractions Date data type. Simplified version of java.util.Date. Helper functions. Refer to data through compares and exchanges. public class Date implements Comparable<Date> Less. Is item v less than w ? { private final int month, day, year; private static boolean less(Comparable v, Comparable w) public Date(int m, int d, int y) only compare dates { return v.compareTo(w) < 0; } { to other dates month = m; day = d; year = y; } Exchange. Swap item in array a[] at index i with the one at index j. public int compareTo(Date that) { if (this.year < that.year ) return -1; private static void exch(Comparable[] a, int i, int j) if (this.year > that.year ) return +1; if (this.month < that.month) return -1; { if (this.month > that.month) return +1; Comparable swap = a[i]; if (this.day < that.day ) return -1; a[i] = a[j]; if (this.day > that.day ) return +1; a[j] = swap; return 0; } } } 11 12 Testing Goal. Test if an array is sorted. private static boolean isSorted(Comparable[] a) { for (int i = 1; i < a.length; i++) if (less(a[i], a[i-1])) return false; 2.1 ELEMENTARY SORTS return true; } ‣ rules of the game ‣ selection sort Algorithms ‣ insertion sort ‣ shellsort ‣ shuffling ROBERT SEDGEWICK | KEVIN WAYNE Q. If the sorting algorithm passes the test, did it correctly sort the array? http://algs4.cs.princeton.edu ‣ convex hull A. 13 Selection sort demo Selection sort ・In iteration i, find index min of smallest remaining entry. Algorithm. ↑ scans from left to right. ・Swap a[i] and a[min]. Invariants. ・Entries the left of ↑ (including ↑) fixed and in ascending order. ・No entry to right of ↑ is smaller than any entry to the left of ↑. initial in final order ↑ 15 16 Selection sort inner loop Selection sort: Java implementation To maintain algorithm invariants: public class Selection { ・Move the pointer to the right. public static void sort(Comparable[] a) { int N = a.length; i++; for (int i = 0; i < N; i++) in final order ↑ { int min = i; ・Identify index of minimum entry on right. for (int j = i+1; j < N; j++) if (less(a[j], a[min])) min = j; int min = i; exch(a, i, min); for (int j = i+1; j < N; j++) } if (less(a[j], a[min])) } in final order ↑ ↑ min = j; private static boolean less(Comparable v, Comparable w) { /* as before */ } ・Exchange into position. private static void exch(Comparable[] a, int i, int j) { /* as before */ } } exch(a, i, min); in final order ↑ ↑ 17 18 Selection sort: mathematical analysis Selection sort: animations 2 20 random items Proposition. Selection sort uses (N – 1) + (N – 2) + ... + 1 + 0 ~ N / 2 compares and N exchanges. a[] entries in black i min 0 1 2 3 4 5 6 7 8 9 10 are examined to find the minimum S O R T E X A M P L E 0 6 S O R T E X A M P L E entries in red 1 4 A O R T E X S M P L E are a[min] 2 10 A E R T O X S M P L E 3 9 A E E T O X S M P L R 4 7 A E E L O X S M P T R 5 7 A E E L M X S O P T R 6 8 A E E L M O S X P T R 7 10 A E E L M O P X S T R 8 8 A E E L M O P R S T X entries in gray are 9 9 A E E L M O P R S T X in final position 10 10 A E E L M O P R S T X A E E L M O P R S T X algorithm position Trace of selection sort (array contents just after each exchange) in final order not in final order Running time insensitive to input. Quadratic time, even if input is sorted. http://www.sorting-algorithms.com/selection-sort Data movement is minimal. Linear number of exchanges. 19 20 Selection sort: animations 20 partially-sorted items 2.1 ELEMENTARY SORTS ‣ rules of the game ‣ selection sort Algorithms ‣ insertion sort ‣ shellsort ‣ shuffling algorithm position ROBERT SEDGEWICK | KEVIN WAYNE in final order http://algs4.cs.princeton.edu ‣ convex hull not in final order http://www.sorting-algorithms.com/selection-sort 21 Insertion sort demo Insertion sort ・In iteration i, swap a[i] with each larger entry to its left. Algorithm. ↑ scans from left to right. Invariants. ・Entries to the left of ↑ (including ↑) are in ascending order. ・Entries to the right of ↑ have not yet been seen.