Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS200: Algorithm Analysis

Similar presentations


Presentation on theme: "CS200: Algorithm Analysis"— Presentation transcript:

1 CS200: Algorithm Analysis

2 QUICKSORT Recursive, Divide and Conquer Algorithm : sorts in place as does insertion sort but unlike mergesort which uses a temporary array. Practical algorithm, as constants hidden in runtime analysis are small. Divide and Conquer Divide : partition array into 2 sub-arrays st elements in lower sub-array <= elements in upper sub-array. Conquer : recursively sort the 2 sub-arrays. Combine : trivial because its an in place sort

3 Key to sort is the partition algorithm, which has a runtime of?
Lumoto's Partition Code (pg. 171) Partition(A, p, r) (*pivot is A[r]*) x = A[r] (*r = last element, p = first*) i = p-1 for j = p to r-1 do if A[j] <= x then i = i+1 swap(A[i], A[j]) swap(A[i+1], A[r]) return i (*new pivot*) Q(n).

4 Do an example trace of partition.

5 QuickSort Pseudo Code Quicksort(A, p, r) if p < r then
Discuss runtime analysis of partition. Hoare’s partition (pg. 185) is faster but more complex. If all elements are not distinct Hoare’s partition gives the best-case split while Lumoto's gives worst-case split. What happens if array is sorted or reverse sorted? QuickSort Pseudo Code Quicksort(A, p, r) if p < r then q = Partition (A, p, r) Quicksort(A, p, q-1) Quicksort(A, q+1, r)

6 Analysis of Quicksort = 2T(n/2) + θ(n)
Assume that all elements are distinct. This ensures that all partition splits have an equal probability of occurring. If we are lucky the partition algorithm evenly splits the array so that (balanced partitioning – best/average) T(n) = ? = 2T(n/2) + θ(n) Use a recurrence tree to confirm runtime analysis of T(n) = Q(nlogn) – looks like MS.

7 If we are unlucky the partition algorithm splits the array so that one partition has no elements and the other has n-1 elements so that T(n) = ? = T(n-1) + T(1) + θ(n) = θ(n2) Use a recurrence tree to confirm runtime analysis. When does worst-case runtime for quicksort occur? Average case runtime of quicksort occurs when all partitions are equally likely so that T(n) = ? = 2T(n/2) + θ(n) = θ(nlg n) We will look at how to solve recurrences before tackling average case runtime analysis.

8 But Intuitive tells us on average …

9 Summary Quicksort functionality
Partition: Lumoto and Hoare’s (see text) partitions Analysis of Quicksort Run time recurrence Average and worst case analysis


Download ppt "CS200: Algorithm Analysis"

Similar presentations


Ads by Google