3
\$\begingroup\$

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)

\$\endgroup\$
2
  • \$\begingroup\$ It works, so far, I didn't found any error. \$\endgroup\$ Commented Oct 4, 2019 at 15:23
  • \$\begingroup\$ OK, just checking. \$\endgroup\$
    – markspace
    Commented Oct 4, 2019 at 15:26

1 Answer 1

1
\$\begingroup\$

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.

\$\endgroup\$

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.