Skip to content

Big O Visualizer

Bubble Sort

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list.

Complexity

Bubble Sort has a linear best-case time complexity, which can be tested using a list of numbers that's already sorted.

Bubble Sort has a quadratic average-case time complexity, which can be tested using a random list of numbers.

Bubble Sort has a quadratic worst-case time complexity, which can be tested using a reversed list of numbers.

Algorithm

Below the implementation of Bubble Sort as used on this page.

src/algorithms/bubble-sort.ts
1export default class BubbleSort extends Algorithm {
2 name = "Bubble Sort"
3 timeComplexityBest = Complexities.linear
4 timeComplexityAverage = Complexities.quadratic
5 timeComplexityWorst = Complexities.quadratic
6
7 execute(array: number[]): void {
8 const len = array.length
9 let swapped
10 do {
11 this.incrementOpCounter()
12 swapped = false
13 for (let i = 0; i < len; i++) {
14 this.incrementOpCounter()
15 if (array[i] > array[i + 1]) {
16 const tmp = array[i]
17 array[i] = array[i + 1]
18 array[i + 1] = tmp
19 swapped = true
20 }
21 }
22 } while (swapped)
23 }
24}