Skip to main content

Quicksort

Definition​

Quicksort is a highly efficient sorting algorithm that works by partitioning an array into smaller sub-arrays, then recursively sorting each sub-array. It follows the divide-and-conquer strategy, making it particularly effective for large datasets

Practice​

quicksort(array, low, high):
if low < high:
// Partition the array and get the pivot index
pivot_index = partition(array, low, high)
// Recursively sort the sub-arrays
quicksort(array, low, pivot_index - 1)
quicksort(array, pivot_index + 1, high)

partition(array, low, high):
// Choose the pivot (here, we choose the last element)
pivot = array[high]
// Index of the smaller element
smaller_index = low - 1

// Iterate through the array from low to high
for j = low to high - 1:
// If current element is smaller than or equal to pivot
if array[j] <= pivot:
// Increment index of smaller element
smaller_index = smaller_index + 1
// Swap smaller element with current element
swap(array, smaller_index, j)

// Swap pivot with element at smaller_index + 1
swap(array, smaller_index + 1, high)
// Return the partitioning index
return smaller_index + 1

swap(array, i, j):
// Swap elements at indices i and j in the array
temp = array[i]
array[i] = array[j]
array[j] = temp