Skip to content

Commit 183df68

Browse files
Code more concise and more readable
1 parent 8fe29ff commit 183df68

File tree

1 file changed

+10
-29
lines changed

1 file changed

+10
-29
lines changed

sorts/quick_sort.py

+10-29
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,9 @@
1010
python quick_sort.py
1111
"""
1212
from __future__ import print_function
13-
from random import shuffle
1413

1514

16-
def sort(collection):
17-
shuffle(collection)
18-
return quick_sort(collection)
19-
20-
21-
def quick_sort(collection):
15+
def quick_sort(ARRAY):
2216
"""Pure implementation of quick sort algorithm in Python
2317
2418
:param collection: some mutable ordered collection with heterogeneous
@@ -35,27 +29,14 @@ def quick_sort(collection):
3529
>>> quick_sort([-2, -5, -45])
3630
[-45, -5, -2]
3731
"""
38-
total_elements = len(collection)
39-
40-
if total_elements <= 1:
41-
return collection
42-
less = []
43-
equal = []
44-
greater = []
45-
pivot = collection[0]
46-
47-
equal.append(pivot)
48-
49-
for i in range(1, total_elements):
50-
element = collection[i]
51-
52-
if element < pivot:
53-
less.append(element)
54-
elif element == pivot:
55-
equal.append(element)
56-
else:
57-
greater.append(element)
58-
return quick_sort(less) + equal + quick_sort(greater)
32+
ARRAY_LENGTH=len(ARRAY)
33+
if(ARRAY_LENGTH<=1):
34+
return ARRAY
35+
else:
36+
PIVOT=ARRAY[0]
37+
GREATER=[element for element in ARRAY[1:] if element>PIVOT]
38+
LESSER=[element for element in ARRAY[1:] if element<=PIVOT]
39+
return quick_sort(LESSER)+[PIVOT]+quick_sort(GREATER)
5940

6041

6142
if __name__ == '__main__':
@@ -70,4 +51,4 @@ def quick_sort(collection):
7051

7152
user_input = input_function('Enter numbers separated by a comma:\n')
7253
unsorted = [int(item) for item in user_input.split(',')]
73-
print(sort(unsorted))
54+
print(quick_sort(unsorted))

0 commit comments

Comments
 (0)