Sort
Introduction
- Goal.Sort any type of data.
How can sort() konw how to compare data of type Double,String,and java.io.File without any information about the type of an item’s key?
Callback = reference to executable 对可执行代码的应用.
- Client passes array of objects to sort() function.
- The sort() function calls back object’s compareTo() method as needed.
Implementing callbacks.
- Java : interfaces.
- C : function pointers.
- C++ : class-type functors.
- C# : delegates.
- python,Perl,ML,Javascript : first-class functions.
Two useful sorting abstractions
Helper functions. Refer to data through compares and exchanges.
Less. Is item v less than w ?
1 | private static boolean less(Comparable v,Comparable w){ |
Exchange. Swap item in array a[] at index i with the one at index j.
1 | private static void exch(Comparable[] a,int i,int j){ |
Goal.Test if an array is sorted.
1 | private static boolean isSorted(Comparable[] a){ |
Q:If the sorting algorithm passes the test,did it correctly sort the array?
A:No.
Selection sort
- In iteration i, find index min of smallest remaining entry.
- Swap a[i] and a[min].
1 | public class Selection{ |
Insertion Sort
- In iteration i, swap a[i] with each larger entry to its left.
- 逆序对
1 | public class Insertion{ |
Shell Sort
1 | public class Shell{ |
Shuffle
两种方法
第一种
Generate a random real number for each array entry.
Sort the array.
Knuth shuffle