Skip to content

Commit fd3130b

Browse files
authored
Merge pull request #91 from gillesigot/master
Added Python quick sort
2 parents b7de63e + 55b4935 commit fd3130b

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
def quickSort(arr):
2+
"""Apply quick sort on the given array
3+
4+
:param arr: the array to sort
5+
:type arr: list
6+
"""
7+
less = []
8+
pivotList = []
9+
more = []
10+
if len(arr) <= 1:
11+
return arr
12+
else:
13+
pivot = arr[0]
14+
for i in arr:
15+
if i < pivot:
16+
less.append(i)
17+
elif i > pivot:
18+
more.append(i)
19+
else:
20+
pivotList.append(i)
21+
less = quickSort(less)
22+
more = quickSort(more)
23+
return less + pivotList + more
24+
25+
# Unit test
26+
a = [4, 65, 2, -31, 0, 99, 83, 782, 1] # The array to sort
27+
a = quickSort(a)
28+
assert all(a[i] <= a[i+1] for i in range(len(a)-1)) # Assert array is sorted
29+
30+
# Quick sort: Quicksort is a comparison sort, meaning that it can
31+
# sort items of any type for which a "less-than" relation is defined.
32+
# In efficient implementations it is not a stable sort, meaning
33+
# that the relative order of equal sort items is not preserved.
34+
# Quicksort can operate in-place on an array, requiring small
35+
# additional amounts of memory to perform the sorting. It is very
36+
# similar to selection sort, except that it does not always choose
37+
# worst-case partition.

0 commit comments

Comments
 (0)