320 likes | 450 Views
Quick Sort. Quick Sort. Divide : Pick any element p as the pivot , e.g, the first element Partition the remaining elements into FirstPart, which contains all elements < p SecondPart, which contains all elements ≥ p Recursively sort the FirstPart and SecondPart
E N D
Quick Sort • Divide: • Pick any element p as the pivot, e.g, the first element • Partition the remaining elements into FirstPart,which contains all elements< p SecondPart, which contains all elements ≥ p • Recursively sort the FirstPart and SecondPart • Combine: no work is necessary since sorting is done in place
Partition Recursive call p p p p ≤ x p ≤ x Sorted FirstPart Sorted SecondPart x < p Quick Sort A: pivot FirstPart SecondPart x < p Sorted
Quick Sort Quick-Sort(A, left, right) ifleft ≥ right return else middle ← Partition(A, left, right) Quick-Sort(A, left, middle–1 ) Quick-Sort(A, middle+1, right) end if
p x < p p p ≤ x x < p p ≤ x p Partition A: A: A: p
Partition Example A: 4 8 6 3 5 1 7 2
Partition Example i=0 A: 4 8 6 3 5 1 7 2 j=1
Partition Example i=0 A: 4 8 6 3 5 1 7 2 8 j=1
Partition Example i=0 A: 4 8 6 6 3 5 1 7 2 j=2
i=1 3 8 Partition Example i=0 A: 4 6 3 5 1 7 2 8 3 j=3
i=1 Partition Example A: 4 3 6 8 5 1 7 2 5 j=4
i=1 Partition Example A: 4 3 6 8 5 1 1 7 2 j=5
i=2 1 6 Partition Example A: 4 3 6 8 5 1 7 2 j=5
i=2 Partition Example A: 7 4 3 1 8 5 6 7 2 j=6
i=2 i=3 Partition Example A: 8 2 2 4 3 1 8 5 6 7 2 j=7
i=3 Partition Example A: 4 3 1 2 5 6 7 8 j=8
i=3 Partition Example A: 4 4 3 1 2 5 6 7 8 2
x < 4 4 ≤ x Partition Example pivot in correct position A: 2 4 3 1 5 6 7 8
Partition(A, left, right) • x ← A[left] • i ← left • for j ← left+1 to right • if A[j] < x then • i ← i + 1 • swap(A[i], A[j]) • end if • end for j • swap(A[i], A[left]) • return i n = right – left +1 Time: cn for some constant c Space: constant
2 3 1 4 5 6 7 8 Quick-Sort(A, 0, 7) Partition A: 4 8 6 3 5 1 7 2
1 3 2 Quick-Sort(A, 0, 7) , partition Quick-Sort(A, 0, 2) A: 5 6 7 8 4 2 3 1
Quick-Sort(A, 0, 7) Quick-Sort(A, 0, 0) , base case , return 5 6 7 8 4 3 1 2 1
3 3 Quick-Sort(A, 0, 7) Quick-Sort(A, 1, 1) , base case 5 6 7 8 4 1 2
1 1 3 3 2 2 Quick-Sort(A, 0, 7) Quick-Sort(A, 0, 2), return Quick-Sort(A, 2, 2),return 5 6 7 8 4
5 6 7 8 6 7 8 5 1 3 2 Quick-Sort(A, 0, 7) Quick-Sort(A, 4, 7) , partition Quick-Sort(A, 2, 2),return 4
1 3 2 6 7 8 Quick-Sort(A, 0, 7) Quick-Sort(A, 5, 7) , partition 4 5 6 6 7 8
1 3 2 Quick-Sort(A, 0, 7) Quick-Sort(A, 6, 7) , partition 4 5 6 7 7 8 8
1 3 2 Quick-Sort(A, 0, 7) , return , base case Quick-Sort(A, 7, 7) 4 5 6 7 8 8
1 3 2 Quick-Sort(A, 0, 7) , return Quick-Sort(A, 6, 7) 4 5 6 7 8
1 3 2 6 7 8 Quick-Sort(A, 0, 7) , return Quick-Sort(A, 5, 7) 4 5
5 1 3 2 6 7 8 Quick-Sort(A, 0, 7) , return Quick-Sort(A, 4, 7) 4
5 1 3 2 6 7 8 Quick-Sort(A, 0, 7) , done! Quick-Sort(A, 0, 7) 4