Typorithm · medium

Quick Sort

▷ Interactive algorithm labquick-sortsortingdivide-and-conquerpartitionrecursion
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Quick Sort

0%

Sorting Algorithms

Quick Sort partitions around a pivot, then recursively sorts the values below and above that pivot.

The base case returns arrays of length 0 or 1 because they are already sorted.

This implementation chooses the last value as the pivot for readability.

Every other value is partitioned into left or right based on whether it is smaller than the pivot.

The final result is sorted left partition, pivot, then sorted right partition.

Average time is O(n log n), but consistently bad pivots can degrade to O(n^2).

Preparing algorithm lab…
01

Pick a pivot.

02

Partition values by comparing with the pivot.

03

Recursively sort both partitions.

04

Average O(n log n), worst O(n^2).

05

This readable version uses extra arrays.

function quickSort(arr) {
  if (arr.length <= 1) return arr;

  const pivot = arr[arr.length - 1];
  const left = [];
  const right = [];

  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i] < pivot) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }

  return [...quickSort(left), pivot, ...quickSort(right)];
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Base case

A length 0 or 1 array is already sorted, so recursion stops.

if (arr.length <= 1) return arr

2. Pivot

This version chooses the final value as the pivot.

const pivot = arr[arr.length - 1]

3. Left partition

Values smaller than the pivot are collected on the left.

const left = []

4. Right partition

Values greater than or equal to the pivot are collected on the right.

const right = []

5. Partition scan

Scan every value except the pivot itself.

for (let i = 0; i < arr.length - 1; i++)

6. Compare with pivot

Each value goes left or right based on the pivot comparison.

arr[i] < pivot

7. Push left

Smaller values go into the left recursive problem.

left.push(arr[i])

8. Join recursive results

Sort the partitions recursively and place the pivot between them.

return [...quickSort(left), pivot, ...quickSort(right)]

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Quick Sort: Visual Walkthrough & Practice · Typorithm | ApplyDjinn