-
Notifications
You must be signed in to change notification settings - Fork 0
/
quick_sort.py
36 lines (30 loc) · 1022 Bytes
/
quick_sort.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
class QuickSort:
def sort(self, array: list):
self.sort_(array, 0, len(array) - 1)
def sort_(self, array: list, i: int, j: int):
if i == j:
return
pivot = self.find_pivot(array, i, j)
k = self.partition(array, i, j, pivot)
self.sort_(array, i, k - 1)
self.sort_(array, k, j)
def find_pivot(self, array: list, i: int, j: int):
for k in range(i + 1, j + 1):
if array[k] > array[i]:
return array[k]
elif array[k] < array[i]:
return array[i]
return array[i]
def partition(self, array: list, i: int, j: int, pivot: int):
while True:
while array[i] < pivot:
i = i + 1
while array[j] >= pivot:
j = j - 1
if i > j:
return i
self.swap(array, i, j)
def swap(self, array: list, i: int, j: int):
temp = array[i]
array[i] = array[j]
array[j] = temp