Lecture 27
Lecture 27
2 1 3 6 5 4
2 1 3 5 6 4
2 1 3 5 4 6 Etc...
1
11/4/2010
Insertion
Selection
Divide-and-conquer
Merge Sort
2
11/4/2010
Quicksort idea
Quicksort
Quicksort was invented in 1960 by Tony Hoare. Choose a pivot.
3
11/4/2010
2 1 3 5 4 6 Etc...
Insertion sort
Naïve Sorting Sorted subarray
for i=1 to n-1 105 47 13 99 30 222
{ for j=0 to n-i-1
if (A[j].compareTo(A[j+1])>0) 47 105 13 99 30 222
swap(A[j], A[j+1]);
if (no swaps) break; 13 47 105 99 30 222
}
What happens if 13 47 99 105 30 222
All keys are equal?
Keys are sorted in reverse order? 13 30 47 99 105 222
Keys are sorted?
keys are randomly distributed? 105 47 13 99 30 222
Exercise: Count the number of operations in bubble sort
and find a Big O analysis for bubble sort
4
11/4/2010
# of slides = O(#inversions)
very fast if array is nearly sorted to begin with
5
11/4/2010
Bucket sort
Bucket
1
sort
3 3 1 2
Bucket sort characteristics
Runs in O(N) time.
Is stable:
If two elements (A,B) are equal with respect to sorting,
and they appear in the input in order (A,B), then they
remain in the same order in the output.
1 2 3
6
11/4/2010
Radix sort
If your integers are in a larger range then do bucket
sort on each digit
What about
Radix sort non-binary?
can be used for decimal numbers and
alphanumeric strings.
0 3 2 0 3 1 0 1 5 0 1 5
2 2 4 0 3 2 0 1 6 0 1 6
0 1 6 2 5 2 1 2 3 0 3 1
0 1 5 1 2 3 2 2 4 0 3 2
0 3 1 2 2 4 0 3 1 1 2 3
1 6 9 0 1 5 0 3 2 1 6 9
1 2 3 0 1 6 2 5 2 2 2 4
2 5 2 1 6 9 1 6 9 2 5 2