Quick Sort Algorithm
Quick Sort Algorithm
Quick Sort is a highly efficient and widely used sorting algorithm that
follows the divide and conquer approach. It works by selecting a pivot
element from the array and partitioning the other elements into two sub-
arrays, according to whether they are less than or greater than the pivot.
Then, it recursively sorts the sub-arrays.
2. Partitioning: Rearrange the array such that elements less than the
pivot are on the left, elements greater than the pivot are on the
right, and the pivot is placed in its correct position. This step is
called partitioning.
Let’s sort the following array using the Quick Sort algorithm:
Step-by-Step Execution:
Let’s choose the last element as the pivot. Here, the pivot is 70.
We rearrange the elements such that elements less than the pivot (70)
are placed to the left and elements greater than the pivot are placed to
the right. We do this by iterating through the array and comparing each
element to the pivot.
Start with the leftmost element (10) and iterate through the array.
Keep a pointer (i) for elements less than the pivot. Start by setting i
= -1.
Iteration:
Array after partitioning: [10, 30, 40, 50, 70, 90, 80]
Now, place the pivot 70 at the correct position (index 4 in this case).
Array after placing pivot: [10, 30, 40, 50, 70, 90, 80]
The left sub-array is [10, 30, 40, 50] (elements less than 70).
Partitioning: After partitioning, the array becomes [10, 30, 40, 50]
(pivot 50 is already in place).
No further sorting is needed because the left sub-array [10, 30, 40]
is already sorted.
After recursively sorting all sub-arrays, the final sorted array is:
Best Case: When the pivot divides the array into two equal halves.
The time complexity is O(nlogn)O(n \log n).
Space Complexity:
The space complexity is O(logn)O(\log n) due to the recursive call stack (if
the pivot divides the array reasonably well).
Conclusion: