AlgoViz

Bubble Sort

Easy

Swap adjacent out-of-order pairs

In simple words

Keep comparing two neighbors and swap them if they're in the wrong order; the biggest slowly bubbles to the end each pass.

The idea

Repeatedly walk the array swapping any adjacent pair that's out of order. Each pass floats the next-largest value to its final spot at the end.

5
2
8
1
9
3
0
1
2
3
4
5

Step 1 of 24. Compare each adjacent pair and swap if they're out of order — the largest value bubbles to the end each pass. Values: 5, 2, 8, 1, 9, 3.

1/24
Brute force
timeO(n²)spaceO(1)

Largest bubbles to the end.

1// bubble the largest to the end each pass2for (let i = 0; i < n - 1; i++) {3  for (let j = 0; j < n - 1 - i; j++) {4    if (a[j] > a[j + 1])5      [a[j], a[j + 1]] = [a[j + 1], a[j]];6  }7}8return a;

Input

array
[5, 2, 8, 1, 9, 3]

Memory

j
j+1

Output

result

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
nums = [5, 1, 4, 2, 8]
Output:
[1, 2, 4, 5, 8]
Explanation:
Bigger values bubble to the end each pass.

Example 2

Input:
nums = [1, 2, 3]
Output:
[1, 2, 3]
Explanation:
Already sorted — one clean pass.

Example 3

Input:
nums = [3, 2, 1]
Output:
[1, 2, 3]
Explanation:
Reversed input flips to order.

Practice this problem:GeeksforGeeks(opens in a new tab)

Finished the walkthrough? Add it to your streak.