Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Quick Sort

Uploaded by

Sơn Nguyễn
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Quick Sort

Uploaded by

Sơn Nguyễn
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 11

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

numbers p numbers greater


less than p than or equal to p

2
I. Basic idea

QUICK-SORT(A, left, right)


1. if left < right then begin
p = PARTITION(A, left, right) ;
QUICK-SORT(A, left, p-1);
QUICK-SORT(A, p+1, right);
end;
2. return A.

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

 Function PARTITION-LEFT(A, left, right)


1. Set a[pivot] = a[left], i = left + 1, j = right;
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, swap a[i] & a[j]
3. Set k = j; swap a[j] & a[pivot]
4. Return k

5
Example
Select pivot

i = 4 & j = 12, swap

i = 5 & j = 10, swap

i = 8 & j = 9, swap

i = 9 & j = 8, end stage.


Return the pivot to actual position
6
Example

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

You might also like