Skip to content### Complexity

### Algorithm

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.

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.

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.linear4 timeComplexityAverage = Complexities.quadratic5 timeComplexityWorst = Complexities.quadratic67 execute(array: number[]): void {8 const len = array.length9 let swapped10 do {11 this.incrementOpCounter()12 swapped = false13 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] = tmp19 swapped = true20 }21 }22 } while (swapped)23 }24}`