Professional Documents
Culture Documents
Sorting Methods
Sorting Methods
Introduction
Assumptions
Sorting an array of integers Entire sort can be done in main memory
Insertion Sort
Idea: Start at position 1 and move each element to the left until it is in the correct place At iteration i, the leftmost i elements are in sorted order
for i = 1; i < a.size(); i++ tmp = a[i] for j = i; j > 0 && tmp < a[j-1]; j-a[j] = a[j-1] a[j] = tmp
i = 2 + 3 + 4 + + N = (N2)
i=2
Calculate average running time of insertion sort by computing average number of inversions
Shell sort
Idea: Use increment sequence h1, h2, ht. After phase using increment hk, a[i] <= a[i+ hk] for each hk for i = hk to a.size() tmp = a[i] for j = i j >= hk && tmp < a[j- hk] j-= hk a[j] = a[j- hk ] a[j] = tmp
Shell sort
Conceptually, separate array into hk columns and sort each column Example:
81 94 11 96 12 35 17 95 28 58 41 75 15
Hibbards increments
1, 3, 7, , 2k-1 (N3/2)
At last pass, ith smallest number will be in position 2i-1 requiring i-1 moves. Total number of moves:
N/2 i=1
i-1 = (N2)
Heap sort
Strategy
Apply buildHeap function Perform N deleteMin operations
Running time is O(NlogN) Problem: Simple implementation uses two arrays N extra space
Heap sort
Solution: After deletion, size of heap shrinks by 1, so simply insert into empty slot Problem: Results in array sorted in decreasing order use max heap instead Example: 97 53 59 26 41 58 31
Merge sort
Recursively sort elements 1-N/2 and N/2N and merge the result This is a classic divide-and-conquer algorithm.
Otherwise
Merge sort left half Merge sort right half Merge
Example 24 13 26 1 2 27 38 15
Quicksort
Base case: Return if number of elements is 0 or 1 Pick pivot v in S. Partition into two subgroups. First subgroup is < v and last subgroup is > v. Recursively quicksort first subgroup and last subgroup
Quicksort
Picking the pivot
Choose first element
Bad for presorted data
Choose randomly
Random number generation can be expensive
Median-of-three
Choose median of left, right, and center Good choice!
Quicksort
Partitioning
Move pivot to end i = start; j = end; i++ and j-- until a[i] > pivot and a[j] < pivot and i<j
swap a[i] and a[j]
Example 13 81 92 43 65 31 57 26 75 0
Quicksort Analysis
Quicksort relation
T(N) = T(i) + T(N-i-1) + cN
Quicksort Analysis
Best-case pivot always middle element
T(N) = 2T(N/2) + cN Can use same analysis as mergesort = O(NlogN)
Decision Tree
a<b a<b<c a<c<b c<a<b a<b<c a<c<b b<a<c b<c<a c<a<b c<b<a c<a c<a<b c<b a<c<b a<c b<a<c b<a b<a<c b<c<a c<b<a
c<b c<b<a
c<a b<c<a
Bucket sort
Sorting algorithm that runs in O(N) time, how? What is special about this algorithm? for i = 1 to n increment count[Ai]