--
Quick Sort: Pseudo-code
Quicksort (a, left, right)
Int i= left, j= right, pivot= i;
For i= 1 to n, i≠j do
{
While (a[++i] < pivot) {}
While (pivot < a[--j]) {} Partitioning
If (i>j)
swap (a[i], a[j])
}
Quicksort (a, left, i-1); Recursion
Quicksort (a, i+1, right);
Quicksort (a, left, right)
Int i= left, j= right, pivot= i;
For i= 1 to n, i≠j do
{
While (a[++i] < pivot) {}
While (pivot < a[--j]) {}
If (i>j)
swap (a[i], a[j])
}
Quicksort (a, left, right)
Int i= left, j= right, pivot= i;
For i= 1 to n, i≠j do
{
While (a[++i] < pivot) {}
While (pivot < a[--j]) {}
If (i>j)
swap (a[i], a[j])
}
Quicksort (a, left, right)
Int i= left, j= right, pivot= i;
For i= 1 to n , i≠j do
{
While (a[++i] < pivot) {}
While (pivot < a[--j]) {}
If (i>j)
swap (a[i], a[j])
}
Quicksort (a, left, right)
Int i= left, j= right, pivot= i;
For i= 1 to n , i≠j do
{
While (a[++i] < pivot) {}
While (pivot < a[--j]) {}
If (i>j)
swap (a[i], a[j])
}
Quicksort (a, left, right)
Int i= left, j= right, pivot= i;
For i= 1 to n , i≠j do
{
While (a[++i] < pivot) {}
While (pivot < a[--j]) {}
If (i>j)
swap (a[i], a[j])
}
Quicksort (a, left, right)
Int i= left, j= right, pivot= i;
For i= 1 to n , i≠j do
{
While (a[++i] < pivot) {}
While (pivot < a[--j]) {}
If (i>j)
swap (a[i], a[j])
}
Quicksort (a, left, right)
Int i= left, j= right, pivot= i;
For i= 1 to n , i≠j do
{
While (a[++i] < pivot) {}
While (pivot < a[--j]) {}
If (i>j)
swap (a[i], a[j])
}
Quicksort (a, left, right)
Int i= left, j= right, pivot= i;
For i= 1 to n , i≠j do
{
While (a[++i] < pivot) {}
While (pivot < a[--j]) {}
If (i>j)
swap (a[i], a[j])
}
10, 80, 30, 90, 40
Best-Case Scenario
• What will be the best case?
– Partition is perfectly balanced.
– Pivot is always in the middle (median of the array).
• This recurrence is similar to the merge sort recurrence.
• The result is O(NlogN).
8 1 3 2 6 5 7 4 12 9 11 10 14
4 1 3 2 6 5 7--8--12 9 11 10 14
125
Worst-Case Scenario
• What will be the worst case?
– Partition is unbalanced.
– Smallest/largest element as a Pivot.
– The result is O(n^2).
13 10 8 6 3
10 8 6 3 13
126
Heap Sort
• Min Heap
• Max Heap
127
Ordered
Analysis
– Best case
– Worst case O(n log n)
– Average case