Beruflich Dokumente
Kultur Dokumente
Session-05 , Spring-07
Chapter 7
Sorting
Example
• 34,8,64,51,32,21
– (34,8), (34, 32), (34, 21) , (64, 51), (64, 32), (64, 21),
(51, 32), (51, 21), and (32, 21)
hk – sorted
Theorem 1
• The worst case running time of Shellsort, using
Shell’s increments, is Q(N2)
Theorem 2
• The worst case running time of Shellsort, using
Hibbard’s increments, is Q(N3/2)
– 1, 3, 7, …, 2k -1
Basic Strategy
• Build a binary heap of N elements
• Perform N DeletMin operations
• Record these elements in a second array and
then copy them back to the first array
• Since each DeletMin takes O(logN) time, so
total running time is O(NlogN)
into a max-heap:
Recurrence equation
T(1) = 1
T(N) = 2T(N/2) + N
N 2
4T ( ) 2 N
4 N N log N
N N
4( 2T ( ) ) 2 N O( N log N )
8 4
N
8T ( ) 3 N
8
N
2 T ( k ) kN
k
2
Copyright © Kashif Javed Sorting 7-44
Chapter 7: Sorting
7.1 Preliminaries
7.2 Insertion Sort
7.3 A Lower Bound for Simple Sorting Algorithms
7.4 Shellsort
7.5 Heapsort
7.6 Mergesort
7.7 Quicksort
Average case
• O(N log N)
Worst case
• O(N2)
• But, the worst case seldom happens
Select pivot
81 43 31 57 75
13 65 26 0
92
partition
13 31 57 81
26 0 65 92 75
43
0 13 26 31 43 57 75 81 92
Merge
0 13 26 31 43 57 65 75 81 92
A safe Maneuver
• choose a random pivot
• but random number generation is expensive
Pivot
• = Median of S[left], S[right], and S[center]
• = median of 6, 8, and 0
• = S[left] = 6
8 1 4 9 0 3 5 2 7 6
pivot
Have two ‘indices’ – i and j
i starts at first element and moves forward
j starts at next-to-last element and moves backwards
8 1 4 9 0 3 5 2 7 6
i j pivot
Copyright © Kashif Javed Sorting 7-52
Quicksort…
While (i < j)
Move i to the right till we find a number greater
than pivot
Move j to the left till we find a number smaller than
pivot
If (i < j) swap(S[i], S[j])
(The effect is to push larger elements to the right
and smaller elements to the left)