Quick Sort
Anjana Silva
Web Team Leader at MYHSM | Sharing daily insights on software engineering for your growth ?? Be sure to follow my profile ?? | Help solving tech problems ?? | Cricket enthusiast ??
Quick sort is a divide-and-conquer algorithm that 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. The sub-arrays are then recursively sorted.
When to use quick sort
? Quick sort is efficient for sorting large datasets.
? It has an average-case time complexity of O(n log n), making it one of the fastest sorting algorithms in practice.
? It is suitable for most types of data and performs well in a wide range of scenarios.
When not to use quick sort:
? Quick sort has a worst-case time complexity of O(n^2) if the pivot selection is poor, which can happen if the input array is already sorted or nearly sorted. However, this can be mitigated by using various pivot selection strategies (e.g., choosing the median of three random elements).
? Quick sort is not stable, meaning it may change the relative order of equal elements in the input array. If stability in sorting is required, another sorting algorithm should be considered.
A simple quick sort example in Python,
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
less_than_pivot = [x for x in arr[1:] if x <= pivot]
greater_than_pivot = [x for x in arr[1:] if x > pivot]
return quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot)
# Example usage:
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = quick_sort(arr)
print("Sorted array is:", sorted_arr)
I hope you enjoyed this post. Thank you.