Back to Home

Quick Sort

An efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order using a pivot.

Visualization

Step 1 / 13
Speed:

Details

Analogy

Imagine a teacher sorting exam papers by score. They pick one paper (the 'pivot'), say with a score of 85. They then create two piles: papers with scores lower than 85 and papers with scores higher than 85. They repeat this process on the two smaller piles until all the papers are sorted.

Purpose

To sort an array by picking an element as a pivot and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot.

Use Cases

One of the most widely used sorting algorithms. It's the default in many programming language libraries due to its good average-case performance.

Algorithm Steps

Line 1
1
function quickSort(arr, low, high):
2
if low < high:
3
pivot = partition(arr, low, high)
4
quickSort(arr, low, pivot-1)
5
quickSort(arr, pivot+1, high)
6
7
function partition(arr, low, high):
8
pivot = arr[high]
9
i = low - 1
10
for j = low to high-1:
11
if arr[j] < pivot:
12
i++
13
swap arr[i] with arr[j]
14
swap arr[i+1] with arr[high]
15
return i+1
Current
Executed
Pending

Explanation

What's Happening?

Step 1/13

Initial array. Let's partition the whole array. Pivot is 70 (last element).

Updates with each step • Clickfor full view

Code Implementation

def quick_sort(arr, low, high):
    if low < high:
        pi = partition(arr, low, high)
        quick_sort(arr, low, pi - 1)
        quick_sort(arr, pi + 1, high)

def partition(arr, low, high):
    pivot = arr[high]
    i = low - 1
    for j in range(low, high):
        if arr[j] < pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return i + 1
Quick Sort - Interactive Visualization | AlgoViz | AlgoViz