Lecture 8 - Quick Sort
Lecture 8 - Quick Sort
Quick Sort
Quick Sort Algorithm
Given an array of n elements (e.g., integers):
If array only contains one element, return
If array contains two element
swap the elements if they are not in-order
Else
pick one element to use as pivot.
Partition elements into two sub-arrays:
Elements less than or equal to pivot
Elements greater than pivot
Quicksort the two sub-arrays
Return results
40 20 13 80 69 50 6 30 100
40 20 13 80 69 50 6 30 100
i j
pivot_index = 0 40 20 13 80 69 50 6 30 100
i j
pivot_index = 0 40 20 13 80 69 50 6 30 100
i j
pivot_index = 0 40 20 13 80 69 50 6 30 100
i j
pivot_index = 0 40 20 13 80 69 50 6 30 100
i j
pivot_index = 0 40 20 13 80 69 50 6 30 100
i j
pivot_index = 0 40 20 13 80 69 50 6 30 100
i j
pivot_index = 0 40 20 13 30 69 50 6 80 100
i j
pivot_index = 0 40 20 13 30 69 50 6 80 100
i j
pivot_index = 0 40 20 13 30 69 50 6 80 100
i j
pivot_index = 0 40 20 13 30 69 50 6 80 100
i j
pivot_index = 0 40 20 13 30 69 50 6 80 100
i j
pivot_index = 0 40 20 13 30 69 50 6 80 100
i j
pivot_index = 0 40 20 13 30 69 50 6 80 100
i j
pivot_index = 0 40 20 13 30 6 50 69 80 100
i j
pivot_index = 0 40 20 13 30 6 50 69 80 100
i j
pivot_index = 0 40 20 13 30 6 50 69 80 100
i j
pivot_index = 0 40 20 13 30 6 50 69 80 100
i j
pivot_index = 0 40 20 13 30 6 50 69 80 100
i j
pivot_index = 0 40 20 13 30 6 50 69 80 100
i j
pivot_index = 0 40 20 13 30 6 50 69 80 100
i j
pivot_index = 0 40 20 13 30 6 50 69 80 100
i j
pivot_index = 0 40 20 13 30 6 50 69 80 100
i j
pivot_index = 0 40 20 13 30 6 50 69 80 100
i j
pivot_index = 4 6 20 13 30 40 50 69 80 100
i j
6 20 13 30 40 50 69 80 100
6 20 13 30 40 50 69 80 100
pivot_index = 0 2 4 10 12 13 50 57 63 100
i j
pivot_index = 0 2 4 10 12 13 50 57 63 100
i j
pivot_index = 0 2 4 10 12 13 50 57 63 100
i j
pivot_index = 0 2 4 10 12 13 50 57 63 100
i j
pivot_index = 0 2 4 10 12 13 50 57 63 100
i j
pivot_index = 0 2 4 10 12 13 50 57 63 100
i j
pivot_index = 0 2 4 10 12 13 50 57 63 100
The best case for quicksort is when each partition stage divides
the input exactly in half. This would make the number of
comparisons used by quicksort satisfy the divide-and-conquer
recurrence
CN = 2CN/2 + N
The 2CN/2 covers the cost of sorting the two sub-lists;
the N is the cost of examining each element, using the partitioning
pointer or the other.
50 By Dr. Farha Al Kharusi, DCS, SQU
Performance Characteristics of Quicksort
Property 2: Quicksort uses about 2N ln N comparisons
on the average.
1 N
CN = N +1+ å(Ck-1 + CN-k ) for N ³ 2
N k=1
C1 = C0 = 0