Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements can then recursively sorts the sub-arrays.

Quicksort is considered to one of the fastest general purpose sorting algorithms even today.

Time complexity:

Average case : n log n

Best case : n log n with simple partition

Worst case : n2

How does the algorithm work?

• Pick an element, called a pivot, from the array.

• Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position.

• Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

The base case of the recursion is arrays of size zero or one, which never need to be sorted.

I will use the Hoare partition scheme for this implementation. It uses two indices that start at the ends of the array being partitioned, then move toward each other, until they detect an inversion: a pair of elements, one greater than or equal to the pivot, one lesser or equal, that are in the wrong order relative to each other. The inverted elements are then swapped. When the indices meet, the algorithm stops and returns the final index.

Implementation:


def quicksort(to_sort, lo, hi):
if lo < hi:
p = partition(to_sort, lo, hi)
quicksort(to_sort, lo, p)
quicksort(to_sort, p + 1, hi)

def partition(to_sort, lo, hi):
pivot = to_sort[lo]
i = lo - 1
j = hi + 1
while True:

i = i + 1
while to_sort[i] < pivot:
i = i + 1

j = j - 1
while to_sort[j] > pivot:
j = j - 1

if i >= j:
return j

temp = to_sort[i]
to_sort[i] = to_sort[j]
to_sort[j] = temp

if __name__ == "__main__":
to_sort = [1,3,2,0,-1,4,5,1,-2,-3,1,7]
quicksort(to_sort, 0 ,len(to_sort)-1)
print(to_sort)


Output:

[-3, -2, -1, 0, 1, 1, 1, 2, 3, 4, 5, 7]


References/code: