Professional Documents
Culture Documents
Introduction
• Assumptions
– Sorting an array of integers
– Entire sort can be done in main memory
Σ i = 2 + 3 + 4 + … + N = θ(N2)
i=2
Sorting – Lower Bound
• Inversion – an ordered pair (i, j) where i < j
but a[i] > a[j]
– Number of swaps required by insertion sort
– Running time of insertion sort O(I+N)
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
Shellsort
• Conceptually, separate array into hk
columns and sort each column
• Example:
81 94 11 96 12 35 17 95 28 58 41 75 15
Shellsort: Analysis
• Increment sequence determines running
time
• Shell’s increments
– ht = floor(N/2) and hk=floor(hk+1/2)
– θ(N2)
• Hibbard’s increments
– 1, 3, 7, …, 2k-1
– θ(N3/2)
Shellsort – Analysis
• Theorem 7.3: The worst-case running time
of Shellsort, using Shell’s increments, is
θ(N2).
• Proof – part 1: There exists some input
that takes Ω(N2). Choose N to be a power
of 2. All increments except last will be
even. Give as input array with N/2 largest
numbers in even positions and N/2
smallest in odd positions.
Shellsort – Analysis
Example: 1 9 2 10 3 11 4 12 5 13 6 14 7 15 8 16
• At last pass, ith smallest number will be in
position 2i-1 requiring i-1 moves. Total
number of moves:
N/2
Σ i-1 = Ω(N2)
i=1
Shellsort – Analysis
• Proof – part 2: A pass with increment hk
performs hk insertion sorts of lists of N/hk
elements. Total cost of a pass is O(hk(N/
hk)2) = O(N2/ hk). Summing over all passes
gives a total bound of
O(sum from 1-t(N2/hi))
= O(N2 (sum from 1-t 1/hi)
= O(N2)
Heapsort
• Strategy
– Apply buildHeap function
– Perform N deleteMin operations
• Example: 97 53 59 26 41 58 31
Mergesort
• Recursively sort elements 1-N/2 and N/2-
N and merge the result
• Otherwise
– Mergesort left half
– Mergesort right half
– Merge
Mergesort – Algorithm
• Merge
leftPos = leftStart; rightPos = rightStart; tmpPos = tmpStart;
while(leftPos <=leftEnd && rightPos <= rightEnd)
if(a[leftPos] <= a[rightPos])
tmpArray[tmpPos++] = a[leftPos++]
else
tmpArray[tmpPos++] = a[rightPos++]
//copy rest of left half
//copy rest of right half
//copy tmpArray back
• Example 24 13 26 1 2 27 38 15
Mergesort – Analysis
• T(1) = 1
• T(N) = 2T(N/2) + N – divide by N
• T(N)/N = T(N/2)/N/2 + 1 – substitute N/2
• T(N/2)/N/2 = T(N/4)/N/4 + 1
• T(N/4)/N/4 = T(N/8)/N/8 + 1 …
• T(2)/2 = T(1)/1 + 1 – telescoping
• T(N)/N = T(1)/1 + logN – mult by N
• T(N) = N + NlogN = O(NlogN)
• Example 13 81 92 43 65 31 57 26 75 0
Quicksort – Analysis
• Quicksort relation
– T(N) = T(i) + T(N-i-1) + cN
• Worst-case – pivot always smallest element
– T(N) = T(N-1) + cN
– T(N-1) = T(N-2) + c(N-1)
– T(N-2) = T(N-3) + c(N-2)
– T(2) = T(1) + c(2) – add previous equations
– T(N) = T(1) + csum([2-N] of i) = O(N2)
Quicksort – Analysis
• Best-case – pivot always middle element
– T(N) = 2T(N/2) + cN
– Can use same analysis as mergesort
– = O(NlogN)
for i = 1 to n
increment count[Ai]