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)
AlexV
7,3532 gold badges24 silver badges47 bronze badges
asked Oct 4, 2019 at 15:07
\$\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\$ 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.

answered Oct 4, 2019 at 18:33
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.