Quicksort
Quicksort
• A key step in the Quicksort algorithm is
partitioning the array
– We choose some (any) number p in the array to use as
a pivot
– We partition the array into three parts:
numbers p numbers greater
less than p than or equal to p
2
Partitioning
• 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
• Interchange (swap) these two elements
• Repeat, searching from where we left off, until
done
3
Example of partitioning
• choose pivot: 4 3 6 9 2 5 3 1 2 1 8 9 3 5 6
• search: 436925312189356
• swap: 433925312189656
• search: 433925312189656
• swap: 433125312989656
• search: 433125312989656
• swap: 433122315989656
• search: 4 3 3 1 2 2 3 1 5 9 8 9 6 5 6 (left > right)
• swap with pivot: 133122345989656
4
Quick Sort Algorithm
void quick_sort(int a[20],int l,int u)
{
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u);
}
} 5
int partition(int a[20],int l,int u)
{ if(i<j)
{
int v,i,j,temp;
temp=a[i];
v=a[l]; a[i]=a[j];
i=l; a[j]=temp;
j=u+1; }
do }while(i<j);
{
a[l]=a[j];
do
a[j]=v;
{ i++; return(j);
}while(a[i]<=v && i<=u); }
do
{ j--;
}while(a[j]>v);
6
Analysis of quicksort—best case
• Each partition operation divides the array
• Then the depth of the recursion in logn
• At each level of the recursion, all the
partitions at that level do work that is linear
in n
• O(logn) * O(n) = O(n logn)
• Hence in the average case, quicksort has
time complexity O(n logn)
• What about the worst case?
7
Partitioning at various levels
8
Worst case
• In the worst case, partitioning always divides the
size n array into these three parts:
– A length one part, containing the pivot itself
– A length zero part, and
– A length n-1 part, containing everything else
• We don’t recur on the zero-length part
• Recurring on the length n-1 part requires (in the
worst case) recurring to depth n-1
9
Worst case partitioning
10
Worst case for quicksort
• In the worst case, recursion may be n levels deep
(for an array of size n)
• But the partitioning work done at each level is still
n
• O(n) * O(n) = O(n2)
• So worst case for Quicksort is O(n2)
11