Skip to content

More concise, optimized and readable code in sorts/quick_sort.py file #73

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 6, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 10 additions & 29 deletions sorts/quick_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,9 @@
python quick_sort.py
"""
from __future__ import print_function
from random import shuffle


def sort(collection):
shuffle(collection)
return quick_sort(collection)


def quick_sort(collection):
def quick_sort(ARRAY):
"""Pure implementation of quick sort algorithm in Python

:param collection: some mutable ordered collection with heterogeneous
Expand All @@ -35,27 +29,14 @@ def quick_sort(collection):
>>> quick_sort([-2, -5, -45])
[-45, -5, -2]
"""
total_elements = len(collection)

if total_elements <= 1:
return collection
less = []
equal = []
greater = []
pivot = collection[0]

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)
ARRAY_LENGTH=len(ARRAY)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good to have spaces before and after operators (f.e.: =, <=, + etc)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I'll do it

if(ARRAY_LENGTH<=1):
return ARRAY
else:
PIVOT=ARRAY[0]
GREATER=[element for element in ARRAY[1:] if element>PIVOT]
LESSER=[element for element in ARRAY[1:] if element<=PIVOT]
return quick_sort(LESSER)+[PIVOT]+quick_sort(GREATER)


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

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