Quick Sort is a divide-and-conquer algorithm that sorts an array by partitioning it into smaller sub-arrays. The central idea is simple – choose a "pivot" element from the array, partition the remaining elements into those that are less than the pivot and those that are greater than the pivot, and then recursively apply the same strategy to the sub-arrays.
Choose a Pivot: Select an element from the array. Different strategies exist for choosing the pivot, such as picking the first element, the last element, or a random one.
Partitioning: Rearrange the array so that all elements with values less than the pivot come before it and all elements with values greater than it come after. After this step, the pivot is in its final position.
Recursive Sort: Recursively apply the same logic to the left and right sub-arrays of the pivot.
Let’s see Quick Sort in action with an example:
[8, 7, 6, 1, 0, 5, 9]
Choosing a Pivot: We choose the last element 9
as the pivot.
Partitioning:
8
(first element) with 9
: 8 < 9
→ keep it.7
: 7 < 9
→ keep it.6
: 6 < 9
→ keep it.1
: 1 < 9
→ keep it.0
: 0 < 9
→ keep it.5
: 5 < 9
→ keep it.9
.9
in its correct position.After partitioning, the array looks like:
[8, 7, 6, 1, 0, 5, 9]
→ 9
is in position 6
.
Recursive Sort:
Now we apply Quick Sort to the left sub-array [8, 7, 6, 1, 0, 5]
.
Choose 5
as the new pivot.
After partitioning, it looks like:
[1, 0, 5, 8, 7, 6]
→ 5
is in position 2
.
Recursively apply Quick Sort to [1, 0]
and [8, 7, 6]
.
Now if we continue this process, we eventually reach the sorted array:
[0, 1, 5, 6, 7, 8, 9]
.
Quick Sort has an average-case time complexity of (O(n \log n)), making it efficient for large datasets. However, in the worst-case scenario (when the smallest or largest element is always chosen as the pivot), the time complexity can degrade to (O(n^2)). This can often be mitigated by using techniques like Randomized Quick Sort or choosing a randomized pivot.
The space complexity of Quick Sort is (O(\log n)) due to the recursive stack space. This is more efficient than some other sorting algorithms like Merge Sort, which requires additional space for merging.
Quick Sort remains an essential algorithm in computer science worth understanding, especially for competitive programming and software development. Its combination of efficiency, adaptability, and the clever use of the divide-and-conquer approach makes it a vital tool in any programmer's arsenal. Whether you're dealing with simple lists or complex datasets, grasping Quick Sort can significantly enhance your ability to manage and manipulate data effectively. Happy sorting!
15/11/2024 | DSA
06/12/2024 | DSA
13/10/2024 | DSA
16/11/2024 | DSA
16/11/2024 | DSA
06/12/2024 | DSA
06/12/2024 | DSA
03/09/2024 | DSA
08/12/2024 | DSA
16/11/2024 | DSA