Skip to content

Commit ba47ae4

Browse files
committed
Quicksort.
1 parent 84d9757 commit ba47ae4

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ Generators
3030
Lists
3131
- Subset with highest sum.
3232
- Find integer in sorted list.
33+
- Merge sort.
34+
- Quicksort.
3335

3436
### Installation
3537
Get the source and run

algorithms/list.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ def find_max_sub(l):
5252
def merge_sort(l):
5353
"""Sort list using merge sort.
5454
55+
Complexity: O(n log n)
56+
5557
@param l list to sort.
5658
@returns sorted list.
5759
"""
@@ -92,3 +94,29 @@ def merge(l1, l2):
9294
h2 = merge_sort(l[mid:])
9395

9496
return merge(h1, h2)
97+
98+
99+
def quicksort(l):
100+
"""Sort list using quick sort.
101+
102+
Complexity: O(n log n). Worst: O(n2)
103+
104+
@param l list to sort.
105+
@returns sorted list.
106+
"""
107+
if len(l) <= 1:
108+
return l
109+
110+
pivot = l[0]
111+
less = []
112+
equal = []
113+
greater = []
114+
for e in l:
115+
if e < pivot:
116+
less.append(e)
117+
elif e == pivot:
118+
equal.append(e)
119+
else:
120+
greater.append(e)
121+
122+
return quicksort(less) + equal + quicksort(greater)

algorithms/tests/test_list.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,5 +45,18 @@ def test_merge_sort_single_element(self):
4545
res = list.merge_sort([3])
4646
self.assertListEqual(res, [3])
4747

48+
def test_quicksort(self):
49+
res = list.quicksort([3, 4, 1, 5, 0])
50+
self.assertListEqual(res, [0, 1, 3, 4, 5])
51+
52+
def test_quicksort_duplicates(self):
53+
res = list.quicksort([3, 4, 1, 5, 4, 0, 1])
54+
self.assertListEqual(res, [0, 1, 1, 3, 4, 4, 5])
55+
56+
def test_quicksort_single_element(self):
57+
res = list.quicksort([3])
58+
self.assertListEqual(res, [3])
59+
60+
4861
if __name__ == '__main__':
4962
unittest.main()

0 commit comments

Comments
 (0)