Quick sort
Partition by Value
It divides the array based on value. It rearranges the element of a given array before partitioning such that all elements before the partitioning position are smaller and all elements after the partitioning position are larger
The algorithm proceeds as follows
The tricky part of the Quick sort is how to achieve the partition.
Choose the pivot element (Usually leftmost (or) rightmost element in the array will act as the pivot element)
And then two scans are been done to bring the smaller elements to left half and larger elements to the right half
Left to right scan (i) - starts with second element of the sub-array and tries to find elements that are larger than the pivot
Right to left scan (j) - starts with the last element of the sub-array and tries to find elements that are smaller than pivot
After the scans are over , three cases may occur
i<j exchange values at i and j, resume the scan
i>j exchange j and pivot
i=j value of pivot and value at j are equal
Analysis of the time complexity
n - Number of elements in the array Basic Operation is the comparison between the elements
Time complexity varies with the input
Let T(n) be the complexity of quick sort. Number of key comparisons made before the partition = n+1 (point where the indices cross over)
In the Worst case, arrays are already in sorted order, partition procedure result in a split where one sub-array is empty and the other sub-array has elements one less than the size of the sub-array being partitioned . Hence if there are n elements, then it takes n+1 comparisons and array is split into {} array and subarray with size n-1 as shown below. After the first iteration , 10 is placed in correct location and Qsort is invoked on remaining set of elements
Test Your Understanding:
Why Quick sort is not stable?
Last updated