This is one of the simplest sorting algorithms. It can be implemented in just a few lines.
def bubble_sort(values):for i in range(0, N):for j in range(i + 1, N):if values[i] > values[j]:values[i], values[j] = values[j], values[i]
The process can be visualized like this:
This is a more complex algorithm, but it runs faster. It works by recursively pivoting the data:
def quicksort_inplace(arr, low, high):if low < high:# Partition the array and get the pivot indexpivot_index = hoare_partition(arr, low, high)# Recursively sort elements before and after the pivotquicksort_inplace(arr, low, pivot_index)quicksort_inplace(arr, pivot_index + 1, high)def hoare_partition(arr, low, high):mid = (low + high) // 2pivot = arr[mid] # Choose the middlde element as the pivot, good choice for rand, sorted, reverse sortedi = low - 1j = high + 1while True:# Move `i` to the right until an element greater than or equal to the pivot is foundi += 1while arr[i] < pivot:i += 1# Move `j` to the left until an element less than or equal to the pivot is foundj -= 1while arr[j] > pivot:j -= 1# If pointers have crossed, return the partition indexif i >= j:return jarr[i], arr[j] = arr[j], arr[i]quicksort_inplace(values, 0, len(values) - 1)
The process can be visualized like this: