Quick Sort
Quick Sort
I. Basic idea
Pick some number p from the array
Move all numbers less than p to the beginning of the array
Move all numbers greater than (or equal to) p to the end of the
array
Quick sort the numbers less than p
Quick sort the numbers greater than or equal to p
2
I. Basic idea
3
II. Algorithm
Choose an array value (say, the first) to use as the
pivot
Starting from the left end, find the first element
that is greater than or equal to the pivot
Searching backward from the right end, find the
first element that is less than the pivot
Swap these two elements
Repeat, searching from where we left off, until
done
4
II. Algorithm
5
Example
Select pivot
i = 8 & j = 9, swap
7
II. Algorithm
Function PARTITION-MID(A, left, right)
1. Set i = left ; j = right; pivot = (left + right -1) /2+1
2. While (i <= j) do
while (A[i] < A[pivot]) do i = i + 1;
while (A[j] > A[pivot]) do j = j – 1;
if i <= j then swap A[i] & A[j]
4. Return j
8
III. Final comments
Quick sort is the fast sorting algorithm but unstable
For optimum efficiency, the pivot must be chosen
carefully. “Median of three” is a good technique for
choosing the pivot
Quick Sort is also tail recursive
9
Animation of sorting algorithms
10
11