-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.py
More file actions
37 lines (27 loc) · 844 Bytes
/
quick_sort.py
File metadata and controls
37 lines (27 loc) · 844 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
26
27
28
29
30
31
32
33
34
35
36
def _quick_sort(array: list, start: int, end: int) -> None:
if start >= end:
return
pivot_index = _partition(array, start, end)
_quick_sort(array, start, pivot_index - 1)
_quick_sort(array, pivot_index + 1, end)
def _partition(array: list, start: int, end: int) -> int:
pivot = array[end]
# Temporary pivot index
i = start - 1
for j in range(start, end):
if array[j] < pivot:
i += 1
_swap(array, i, j)
i += 1
_swap(array, i, end)
return i
def _swap(array: list, i: int, j: int) -> None:
temp = array[i]
array[i] = array[j]
array[j] = temp
def quick_sort(array: list) -> None:
"""
Time complexity: worst case - O(n^2) | average case - O(n log n)
Space complexity: O(log n)
"""
_quick_sort(array, 0, len(array) - 1)