I'm new to the world of python, and wrote this quick sort implementation which was taught to us in an algorithms class. I would like to learn to write code less like C++ and more pythonic. Could you review my code to make it more pythonic and less buggy? (I'm sure a class implementation is better, but if the scope of the review could maintain the original structure that would be great).
def quick_sort(A):
#here we choose pivot's index
def choose_pivot(start, end, method='start'):
if start == end: return 0
if method == 'random':
return random.randint(start, end-1)
elif method == 'start':
return start
#we partition the array around the pivot, and return the new pivot
#which is pivot's rightful index
#Hoare's algorithm for partitioning
def partition_array(start, end, pivot_index):
pivot = A[pivot_index]
#move pivot to start of the array, for swap later
A[start], A[pivot_index] = A[pivot_index], A[start]
left, right = start + 1, end - 1
#partition around pivot
while left < right:
while left < end and A[left] < pivot:
left += 1
while right > start and A[right] >= pivot:
right -= 1
if left < right:
A[left], A[right] = A[right], A[left]
#swap back the pivot
A[start], A[right] = A[right], A[start]
return right
#Lumoto's algorithm for partitioning
def partition_array_2(start, end, pivot_index):
left = right = start + 1
pivot = A[pivot_index]
#swap out the pivot to the start of the array
A[pivot_index], A[start] = A[start], A[pivot_index]
while right < end:
if A[right] < pivot:
A[left], A[right] = A[right], A[left]
left += 1
right += 1
#swap back the pivot to its rightful place
A[start], A[left-1] = A[left-1], A[start]
return left-1
#recursively compute quicksort, with divide and conquer
#where start <= new partition (actual place of pivot) <= end
def quick_sort_helper(start, end):
if end - start <= 0:
return
#choose new pivot
pivot_index = choose_pivot(start, end)
new_pivot_index = partition_array_2(start, end, pivot_index)
quick_sort_helper(start, new_pivot_index)
quick_sort_helper(new_pivot_index+1, end)
#Main call
quick_sort_helper(0, len(A))
sorted
orlist.sort
. Which I don't think are the wanted answer :) \$\endgroup\$