Quick Sort

Efficient divide-and-conquer sorting algorithm

Algorithm Code

Time: O(n log n) | Space: O(log n)

1function quickSort(arr, low, high) {
2  if (low < high) {
3    pi = partition(arr, low, high)
4    quickSort(arr, low, pi - 1)
5    quickSort(arr, pi + 1, high)
6  }
7}
8
9function partition(arr, low, high) {
10  pivot = arr[high]
11  i = low - 1
12  for j = low to high - 1:
13    if arr[j] <= pivot:
14      i++
15      swap(arr[i], arr[j])
16  swap(arr[i + 1], arr[high])
17  return i + 1
18}

Algorithm Steps

Step 1 of 38

1

Initial array

2

Set pivot at index 6

3

Compare index 0 with pivot

4

Compare index 1 with pivot

5

Compare index 2 with pivot

6

Compare index 3 with pivot

7

Compare index 4 with pivot

8

Compare index 5 with pivot

9

Move pivot to index 6

10

Mark index 6 as sorted

11

Set pivot at index 5

12

Compare index 0 with pivot

13

Compare index 1 with pivot

14

Compare index 2 with pivot

15

Compare index 3 with pivot

16

Compare index 4 with pivot

17

Move pivot to index 0

18

Mark index 0 as sorted

19

Set pivot at index 5

20

Compare index 1 with pivot

21

Compare index 2 with pivot

22

Compare index 3 with pivot

23

Compare index 4 with pivot

24

Move pivot to index 5

25

Mark index 5 as sorted

26

Set pivot at index 4

27

Compare index 1 with pivot

28

Compare index 2 with pivot

29

Compare index 3 with pivot

30

Swap index 1 and 3

31

Move pivot to index 2

32

Mark index 2 as sorted

33

Mark index 1 as sorted

34

Set pivot at index 4

35

Compare index 3 with pivot

36

Move pivot to index 3

37

Mark index 3 as sorted

38

Mark index 4 as sorted

Quick Sort Visualization

Pivot: None | Comparing: None

64
0
34
1
25
2
12
3
22
4
11
5
90
6
Normal
Pivot
Comparing
Swapping
Sorted
Step 0 of 370%
0.25x4x