\$\begingroup\$
\$\endgroup\$
I was wondering if there is anything that I could do to make my code look cleaner and more descriptive for educational purposes?
def quick_sort(array, start, end):
if start < end:
pivot_index = partition(array, start, end)
quick_sort(array, start, pivot_index - 1)
quick_sort(array, pivot_index + 1, end)
def partition(array, start, end):
pivot_index = start
pivot = array[end]
for loop_index in range(start, end):
if array[loop_index] <= pivot:
array[pivot_index], array[loop_index] = array[loop_index], array[pivot_index]
pivot_index += 1
array[pivot_index], array[end] = array[end], array[pivot_index]
return pivot_index
2 Answers 2
\$\begingroup\$
\$\endgroup\$
- If you want your code cleaner and more descriptive, try adding some English text somewhere. I usually find docstrings are the right place to start in python. What does
partition
do? What doesquick_sort
do? In general by "what does X do?", I mean what does it take in as input, and what does it return--the reader of a docstring doesn't care what happens in between. Read the standard library function descriptions for nice examples. - Right now there is no clear entry point--
quick_sort
takes in three values, which is not what a user would like. Add a function which takes in an array and returns the sorted array. You could either add a new function, or default values for the extra two arguments ofquick_sort
. Both are common.
answered Sep 17, 2021 at 21:30
\$\begingroup\$
\$\endgroup\$
2
Code is clear and straight forward to read. However, there are two assumptions here
- It will be used with data types for which "<=" operation is defined. It is good idea to extract this part comparator and let caller decide how two members should be compared.
- array[end] is always good pivot. This may not be always true. Good pivot is critical for quick sort effectiveness. Input randomisation is commonly used to make good pivot selection more probable.
-
\$\begingroup\$ Could you expand on what "Input randomisation" is. I've not come across this before and don't understand what you mean by your answer as is. I feel I could learn something here, but I'm just not able to connect the dots. \$\endgroup\$2021年09月17日 18:36:26 +00:00Commented Sep 17, 2021 at 18:36
-
lang-py