3
\$\begingroup\$

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
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$
  • 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 does quick_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 of quick_sort. Both are common.
\$\endgroup\$
1
\$\begingroup\$

Code is clear and straight forward to read. However, there are two assumptions here

  1. 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.
  2. 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.
\$\endgroup\$
2
  • \$\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\$
    – Peilonrayz
    Commented Sep 17, 2021 at 18:36
  • \$\begingroup\$ @Peilonrayz Here, this might help you. \$\endgroup\$
    – Farzin
    Commented Sep 18, 2021 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.