Skip to content

Commit 7417932

Browse files
committed
Added Quick Sort Program
1 parent 03a4251 commit 7417932

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

divide_and_conquer/quicksort.py

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
from __future__ import annotations
2+
3+
def partition(array: list, start: int, end: int) -> int:
4+
"""Helper function for Quick Sort.
5+
6+
>>> array = [5, 8, 3, 2, 9, 6]
7+
>>> start = 0
8+
>>> end = 5
9+
>>> index = partition(array, start, end)
10+
>>> index # The pivot index
11+
3
12+
>>> sorted(array[:index]) # Elements less than pivot
13+
[2, 3, 5]
14+
>>> sorted(array[index+1:]) # Elements greater than pivot
15+
[8, 9]
16+
17+
>>> array = []
18+
>>> start = 0
19+
>>> end = 0
20+
>>> partition(array, start, end)
21+
0
22+
>>> array
23+
[]
24+
"""
25+
if not array:
26+
return 0
27+
pivot = array[end]
28+
index = start - 1
29+
for j in range(start, end):
30+
if array[j] <= pivot:
31+
index += 1
32+
array[index], array[j] = array[j], array[index]
33+
array[index+1], array[end] = array[end], array[index+1]
34+
return index+1
35+
36+
def quicksort(array, start, end):
37+
"""Returns a list of sorted array elements using Quick Sort.
38+
39+
>>> from random import shuffle
40+
>>> array = [5, 8, 3, 2, 9, 6]
41+
>>> start = 0
42+
>>> end = 5
43+
>>> quicksort(array, start, end)
44+
>>> array
45+
[2, 3, 5, 6, 8, 9]
46+
47+
>>> shuffle(array)
48+
>>> quicksort(array, start, end)
49+
>>> array
50+
[2, 3, 5, 6, 8, 9]
51+
52+
>>> array = [-100]
53+
>>> quicksort(array, 0, len(array) - 1)
54+
>>> array
55+
[-100]
56+
57+
>>> array = []
58+
>>> quicksort(array, 0, 0)
59+
>>> array
60+
[]
61+
"""
62+
if start < end:
63+
partition_index = partition(array, start, end)
64+
quicksort(array, start, partition_index-1)
65+
quicksort(array, partition_index+1, end)
66+
67+
if __name__ == "__main__":
68+
import doctest
69+
doctest.testmod()

0 commit comments

Comments
 (0)