Quick sort
Quick Sort Quick sort is an efficient sorting algorithm that employs a divide-and-conquer approach to arrange an array of elements. It follows the following...
Quick Sort Quick sort is an efficient sorting algorithm that employs a divide-and-conquer approach to arrange an array of elements. It follows the following...
Quick Sort
Quick sort is an efficient sorting algorithm that employs a divide-and-conquer approach to arrange an array of elements. It follows the following steps:
Divide: Divide the array into two halves, usually by selecting the middle element as the pivot.
Conquer: Arrange the two halves recursively, with the pivot element placed in its correct sorted position within each subarray.
Combine: Merge the two sorted halves into a single sorted list by comparing the pivot elements and inserting them in their proper positions based on their sorted order.
Example:
Consider the following unsorted array:
[8, 7, 9, 1, 3]
Divide:
Pivot: 8 (middle element)
Left subarray: [7, 9, 1]
Right subarray: [8, 3]
Conquer:
Left subarray is sorted in ascending order.
Right subarray is sorted in descending order.
Combine:
Merge the two sorted subarrays side by side, starting with the leftmost elements.
The pivot element (8) is placed in its correct sorted position within the merged subarray.
Time Complexity:
Quick sort has a time complexity of O(n log n), where n is the length of the input array. This means that on average, the algorithm will divide the array into approximately log n subarrays, resulting in a linear number of comparisons and swaps.
Space Complexity:
Quick sort has a space complexity of O(log n), similar to its time complexity. It requires an additional O(log n) amount of memory to store the recursive calls and the merged sorted subarrays.
Advantages:
Efficient for large arrays.
Stable (preserves the relative order of equal elements).
Highly optimized for specific hardware architectures.
Disadvantages:
Not as efficient for small arrays.
Can be susceptible to the "pivot effect," where the pivot element dominates the sorting process.
Not suitable for all types of data, such as strings or arrays with specific character distributions