2. Quick Sort
Quicksort is a divide-and-conquer sorting
algorithm in which division is dynamically
carried out (as opposed to static division in
Mergesort).
3. The three steps of Quicksort are as follows:
• Divide: Rearrange the elements and split the array into two subarrays
and an element in between such that so that each element in the left
subarray is less than or equal the middle element and each element
in the right subarray is greater than the middle element.
• Conquer: Recursively sort the two subarrays.
• Combine: None.
Quick Sort
4.
5.
6. 15 20 5 30 35 10 ∞
20 < 15 false so stop
∞<= 1510 > 15 false
so stop
i =2
m =1
j =7
i< j, interchange a[i] with a[j]
15 10 5 30 35 20 ∞
i < j (3 <6), true so continue in loop with i=2 and j=6
15 10 5 30 35 20 ∞
5 <15
true
30 <15 false so stop for I = 4
35 >15 true
30>15
i =3
m =1
j =5
i< j, false, so no interchange.
Repeat condition becomes true, So stop looping. interchange a[m] with a[j]
5>15 false so
stop for j=3
5 10 15 30 35 20 ∞
Return j=3 as new pivot element
7. 30 35 20 ∞
35>=30
20 <=30i =4
m =4
j =7
i< j, interchange a[i] with a[j] => 5< 6 , so change a[5] with a[6]
30 20 35 ∞
i < j, (5 < 6) true so continue in loop With i=5 and j=6
30 20 35 ∞
35 >3020 <30i =6
m =4
j =5
i< j, false,No interchange.
While(i<j) becomes false , So stop looping .interchange a[m] with a[j]
Return j=5 as new pivot element
Two partitions: partition(a,1,2) and partition(a,4,7)
20 30 35 ∞
8. Quick Sort Call Tree
p = 1, q = 6
j = 3
p = 4, q = 6
j = 5
p = 1, q = 2
j = 1
p = 2, q = 2
return
p = 1, q = 0
return
p = 6, q = 6
return
p = 4, q = 4
return
Though this tree seems balanced, in Quick Sort the tree is not always balanced
because the partition position j will change according to its position in sorting
order. This position will change according to input array.
So best case is that array always splits in middle.
Worst case is left or right skewed.
Average case is array can split at any position s.