mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-19 00:37:02 +00:00
Merge pull request #73 from alaouimehdi1995/master
More concise, optimized and readable code in sorts/quick_sort.py file
This commit is contained in:
commit
408c5d0e80
|
@ -10,15 +10,9 @@ For manual testing run:
|
||||||
python quick_sort.py
|
python quick_sort.py
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
from __future__ import print_function
|
||||||
from random import shuffle
|
|
||||||
|
|
||||||
|
|
||||||
def sort(collection):
|
def quick_sort(ARRAY):
|
||||||
shuffle(collection)
|
|
||||||
return quick_sort(collection)
|
|
||||||
|
|
||||||
|
|
||||||
def quick_sort(collection):
|
|
||||||
"""Pure implementation of quick sort algorithm in Python
|
"""Pure implementation of quick sort algorithm in Python
|
||||||
|
|
||||||
:param collection: some mutable ordered collection with heterogeneous
|
:param collection: some mutable ordered collection with heterogeneous
|
||||||
|
@ -35,27 +29,14 @@ def quick_sort(collection):
|
||||||
>>> quick_sort([-2, -5, -45])
|
>>> quick_sort([-2, -5, -45])
|
||||||
[-45, -5, -2]
|
[-45, -5, -2]
|
||||||
"""
|
"""
|
||||||
total_elements = len(collection)
|
ARRAY_LENGTH = len(ARRAY)
|
||||||
|
if( ARRAY_LENGTH <= 1):
|
||||||
if total_elements <= 1:
|
return ARRAY
|
||||||
return collection
|
else:
|
||||||
less = []
|
PIVOT = ARRAY[0]
|
||||||
equal = []
|
GREATER = [ element for element in ARRAY[1:] if element > PIVOT ]
|
||||||
greater = []
|
LESSER = [ element for element in ARRAY[1:] if element <= PIVOT ]
|
||||||
pivot = collection[0]
|
return quick_sort(LESSER) + [PIVOT] + quick_sort(GREATER)
|
||||||
|
|
||||||
equal.append(pivot)
|
|
||||||
|
|
||||||
for i in range(1, total_elements):
|
|
||||||
element = collection[i]
|
|
||||||
|
|
||||||
if element < pivot:
|
|
||||||
less.append(element)
|
|
||||||
elif element == pivot:
|
|
||||||
equal.append(element)
|
|
||||||
else:
|
|
||||||
greater.append(element)
|
|
||||||
return quick_sort(less) + equal + quick_sort(greater)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
@ -69,5 +50,5 @@ if __name__ == '__main__':
|
||||||
input_function = input
|
input_function = input
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by a comma:\n')
|
user_input = input_function('Enter numbers separated by a comma:\n')
|
||||||
unsorted = [int(item) for item in user_input.split(',')]
|
unsorted = [ int(item) for item in user_input.split(',') ]
|
||||||
print(sort(unsorted))
|
print( quick_sort(unsorted) )
|
||||||
|
|
Loading…
Reference in New Issue
Block a user