I have implemented an iterative in-place quicksort algorithm in Python, which by default selects the pivot as the last element:
def quicksort(array):
"""
Sorts an array of integers using the quick-sort algorithm.
:param array: the array to be sorted
:type array: list<int>
:return: the sorted array
:rtype: list<int>
"""
indexes_stack = list()
idx = (0, len(array) - 1)
indexes_stack.append(idx)
for idx in indexes_stack:
elem_idx = idx[0]
pivot_idx = idx[1]
while pivot_idx > elem_idx:
pivot = array[pivot_idx]
elem = array[elem_idx]
if elem > pivot:
array[pivot_idx] = elem
array[elem_idx] = array[pivot_idx - 1]
array[pivot_idx - 1] = pivot
pivot_idx -= 1
else:
elem_idx += 1
boundar_low = idx[0]
boundar_high = idx[1]
if pivot_idx > 1 and boundar_low < pivot_idx - 1:
indexes_stack.append((boundar_low, pivot_idx - 1))
if pivot_idx < len(array) -1 and pivot_idx + 1 < boundar_high:
indexes_stack.append((pivot_idx + 1, boundar_high))
return array
# Test the sorting function
counter = 0
while counter < 1000:
test = [int(100 * random.random()) for i in xrange(15)]
assert (quicksort(list(test)) == sorted(test)), test
counter += 1
I've tested it with various inputs and it seems to be correct, but I wonder if it can become more efficient or clean.