Skip to content

Commit c5d765d

Browse files
committed
Quicksort in Python.
1 parent 96a4db0 commit c5d765d

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed

quick_sort/main.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
from quick_sort import QuickSort
2+
3+
4+
def is_sorted(numbers):
5+
last_num = float("-inf")
6+
7+
for num in numbers:
8+
if num < last_num:
9+
return False
10+
else:
11+
last_num = num
12+
13+
return True
14+
15+
16+
def contain_same_ints(arr1, arr2):
17+
for i in arr1:
18+
found = False
19+
for j in arr2:
20+
if i == j:
21+
found = True
22+
if not found:
23+
return False
24+
25+
return True
26+
27+
def main():
28+
original = [325432, 989, 547510, 3, -93, 189019, 5042, 123,
29+
597, 42, 7506, 184, 184, 2409, 45, 824,
30+
4, -2650, 9, 662, 3928, -170, 45358, 395,
31+
842, 7697, 110, 14, 99, 221]
32+
33+
numbers = original[:]
34+
35+
qs = QuickSort(numbers)
36+
output = qs.sort()
37+
38+
if is_sorted(output):
39+
print("** SUCCESS! **")
40+
else:
41+
print("Uh oh - not in order.")
42+
43+
if contain_same_ints(original, numbers):
44+
print("** Contain the same elements! **")
45+
else:
46+
print("Uh oh - something is missing.")
47+
48+
print(output)
49+
50+
51+
if __name__ == "__main__":
52+
main()

quick_sort/quick_sort.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import random
2+
3+
4+
class QuickSort(object):
5+
6+
def __init__(self, numbers):
7+
self.values = numbers
8+
self.count = len(self.values)
9+
10+
def sort(self):
11+
self.quick_sort(0, self.count - 1)
12+
return self.values
13+
14+
def quick_sort(self, left, right):
15+
if left == right:
16+
return
17+
18+
i = left
19+
j = right
20+
21+
pivot_index = random.randint(left, right)
22+
23+
pivot = self.values[pivot_index]
24+
25+
while i <= j:
26+
while self.values[i] < pivot:
27+
i += 1
28+
while self.values[j] > pivot:
29+
j -= 1
30+
if i <= j:
31+
if i < j:
32+
temp = self.values[i]
33+
self.values[i] = self.values[j]
34+
self.values[j] = temp
35+
i += 1
36+
j -= 1
37+
38+
if left < j:
39+
self.quick_sort(left, j)
40+
if right > i:
41+
self.quick_sort(i, right)

0 commit comments

Comments
 (0)