forked from jwasham/practice-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quick_sort.py
39 lines (30 loc) · 911 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
37
38
39
import random
class QuickSort(object):
def __init__(self, numbers):
self.values = numbers
self.count = len(self.values)
def sort(self):
self.quick_sort(0, self.count - 1)
return self.values
def quick_sort(self, left, right):
if left == right:
return
i = left
j = right
pivot_index = random.randint(left, right)
pivot = self.values[pivot_index]
while i < j:
while self.values[i] < pivot:
i += 1
while self.values[j] > pivot:
j -= 1
if i <= j:
temp = self.values[i]
self.values[i] = self.values[j]
self.values[j] = temp
i += 1
j -= 1
if left < j:
self.quick_sort(left, j)
if right > i:
self.quick_sort(i, right)