-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.py
More file actions
25 lines (22 loc) · 879 Bytes
/
Copy pathquick_sort.py
File metadata and controls
25 lines (22 loc) · 879 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def quick_sort(arr, reverse=False):
"""
In place and Unstable Sorting method
TC - O(n log n) on average, O(n^2) in the worst case
SC - O(log n) on average (for recursion stack)
"""
def partition(arr, low, high, reverse):
compare = lambda x, y: x < y if reverse else x > y
piv = arr[high]
i = low - 1
for j in range(low, high):
if compare(piv, arr[j]):
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quick_sort_recursive(arr, low, high, reverse):
if low < high:
piv = partition(arr, low, high, reverse)
quick_sort_recursive(arr, low, piv - 1, reverse)
quick_sort_recursive(arr, piv + 1, high, reverse)
quick_sort_recursive(arr, 0, len(arr) - 1, reverse)