-
Notifications
You must be signed in to change notification settings - Fork 43
/
quick_sort_v2.py
57 lines (46 loc) · 1.27 KB
/
quick_sort_v2.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#---------------------------------------------------------------
# QUICK SORT V2
#---------------------------------------------------------------
# https://leetcode.com/explore/learn/card/recursion-ii/470/divide-and-conquer/2870/
# https://rust-algo.club/sorting/quicksort/index.html
"""
Time complexity
Best : O(N Log N)
Avg : O(N Log N)
Worst : O(N Log N)`
Space complexity
O(N)
"""
def quicksort(lst):
"""
Sorts an array in the ascending order in O(n log n) time
:param nums: a list of numbers
:return: the sorted list
"""
n = len(lst)
qsort(lst, 0, n - 1)
def qsort(lst, lo, hi):
"""
Helper
:param lst: the list to sort
:param lo: the index of the first element in the list
:param hi: the index of the last element in the list
:return: the sorted list
"""
if lo < hi:
p = partition(lst, lo, hi)
qsort(lst, lo, p - 1)
qsort(lst, p + 1, hi)
def partition(lst, lo, hi):
"""
Picks the last element hi as a pivot
and returns the index of pivot value in the sorted array
"""
pivot = lst[hi]
i = lo
for j in range(lo, hi):
if lst[j] < pivot:
lst[i], lst[j] = lst[j], lst[i]
i += 1
lst[i], lst[hi] = lst[hi], lst[i]
return i