Quick Sort
Divide and Conqure.
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0] # select first element as the base number
less_than_pivot = [x for x in arr[1:] if x <= pivot] # elements less than the base
greater_than_pivot = [x for x in arr[1:] if x > pivot] # elements bigger than the base
return quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot) # Beautiful ~
# Sample
data = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print("Original:", data)
sorted_data = quick_sort(data)
print("After:", sorted_data)
# Original: [54, 26, 93, 17, 77, 31, 44, 55, 20]
# After: [17, 20, 26, 31, 44, 54, 55, 77, 93]
Complexity
Type | Complexity |
---|---|
Time | O(n*log2 n) -> logn |
Space | O(1) |
Stability
Not Stable