Implemented the quick sort algorithm in python, It was just for learning it, now I want to port it to C.
Thoughts on the quality of my python implementation?
from random import randint, shuffle
def swap(array, a, b):
array[a], array[b] = array[b], array[a]
def quick_sort(array, start=0, end=None):
if end is None:
end = len(array) - 1
if end - start >= 1:
pivot = array[end]
a = start
b = end - 1
while not a > b:
if not array[a] > pivot:
a += 1
continue
else:
if array[b] < pivot:
swap(array, a, b)
a += 1
b -= 1
swap(array, a, end)
quick_sort(array, start, a - 1)
quick_sort(array, a + 1, end)
arr = [randint(0, 30) for _ in range(20)]
print(arr)
quick_sort(arr)
print(arr)
-
\$\begingroup\$ It works, so far, I didn't found any error. \$\endgroup\$StackOverflowToxicityVictim– StackOverflowToxicityVictim2019年10月04日 15:23:36 +00:00Commented Oct 4, 2019 at 15:23
-
\$\begingroup\$ OK, just checking. \$\endgroup\$markspace– markspace2019年10月04日 15:26:56 +00:00Commented Oct 4, 2019 at 15:26
1 Answer 1
Magic Numbers
arr = [randint(0, 30) for _ in range(20)]
What are 0
, 30
, and 20
supposed to represent? I would assign these to variables to make it more clear
Type Hints
This
def swap(array, a, b):
can be this
def swap(array: list, a: int, b: int) -> None:
These allow you to show what types of parameters are accepted, and what types are returned from the functions.
Main Guard
This
arr = [randint(0, 30) for _ in range(20)]
print(arr)
quick_sort(arr)
print(arr)
should be put in a main guard, like so
if __name__ == '__main__':
arr = [randint(0, 30) for _ in range(20)]
print(arr)
quick_sort(arr)
print(arr)
This prevents this code from running if you decide to import this module from another module/program.
Explore related questions
See similar questions with these tags.