10
10
python quick_sort.py
11
11
"""
12
12
from __future__ import print_function
13
- from random import shuffle
14
13
15
14
16
- def sort (collection ):
17
- shuffle (collection )
18
- return quick_sort (collection )
19
-
20
-
21
- def quick_sort (collection ):
15
+ def quick_sort (ARRAY ):
22
16
"""Pure implementation of quick sort algorithm in Python
23
17
24
18
:param collection: some mutable ordered collection with heterogeneous
@@ -35,27 +29,14 @@ def quick_sort(collection):
35
29
>>> quick_sort([-2, -5, -45])
36
30
[-45, -5, -2]
37
31
"""
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 )
59
40
60
41
61
42
if __name__ == '__main__' :
@@ -69,5 +50,5 @@ def quick_sort(collection):
69
50
input_function = input
70
51
71
52
user_input = input_function ('Enter numbers separated by a comma:\n ' )
72
- unsorted = [int (item ) for item in user_input .split (',' )]
73
- print (sort (unsorted ))
53
+ unsorted = [ int (item ) for item in user_input .split (',' ) ]
54
+ print ( quick_sort (unsorted ) )
0 commit comments