Quick Sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and the other array holds values greater than the pivot value.
Basic Steps
- Choose a Pivot: Select a pivot element from the array. The choice of pivot can be random or fixed.
- Partition: Rearrange the array by putting all smaller elements to the left of the pivot and all larger elements to the right of the pivot.
- Recursively Apply: Recursively apply the above steps to the sub-array of elements with smaller values and the sub-array of elements with larger values.
Example
Here is a simple implementation of Quick Sort in Python:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# Test
arr = [3, 6, 8, 10, 1, 2, 1]
print(quick_sort(arr))
Performance
Quick Sort is very efficient for large datasets. Its average and worst-case complexity are O(n log n) and O(n^2), respectively. However, its worst-case scenario is rare in practice.
More Information
For a deeper understanding of Quick Sort, you might want to check out our Sorting Algorithms Guide.
Quick Sort is widely used in various applications due to its efficiency. If you're interested in learning more about sorting algorithms, don't miss our Sorting Algorithms Guide.