In: Computer Science
Using an example of 6 integer elements,
Show how quick sort can be done. [4 Marks]
Describe the worst case scenario of quick sort [2 Marks]
In your answer at d (i), show what makes quick sort categorized as divide and conquer
[2 marks]
Consider the following array: 45,20,5,15,55,30 We need to sort this array in the most efficient manner without using extra place (inplace sorting).
Solution
Step 1:
20, 45, 5, 15, 55,
3020, 5, 45,
15, 55, 30.20, 5, 15, 45, 55, 30. Now 55 is greater than
pivot (30), hence no changes.Thus the pivot (30) comes at its actual position and all elements to its left are lesser, and all elements to the right are greater than itself.
Step 2: The main array after the first step becomes
20, 5, 15, 30, 55, 45
Step 3: Now the list is divided into two parts:
Step 4: Repeat the steps for the left and right
sublists recursively. The final array thus becomes
5, 15, 20, 30, 45, 55
Worst case scenario: This happens when we
encounter the most unbalanced partitions possible, then the
original call takes n time, the recursive call on
n-1 elements will take (n-1) time, the
recursive call on (n-2) elements will take
(n-2) time, and so on. The worst case time complexity
of Quick Sort would be O(n2).
Its
work by selecting a pivot element from the array and partitioning
the other elements into sub arrays, whether they are smaller or
greater than the pivot. The the sub array are sorted recursively.
That is why it came under divide and conqer approach.