Bubble Sort Algorithm

Claire Lee
2 min readSep 16, 2022

--

A in-place sorting algorithm that repeatedly compares two adjacent elements and swaps them if they are out of order. This algorithm is rarely applied in the real world because of its poor performance(O(n²)).

Bubble sort summary card

How Does Bubble Sort Algorithm Work?

Bubble sort algorithm traverses through the array and compare two adjacent elements from left to right. If the set of elements are out of order, swap them. It repeats this process until all the elements are in a correct order.

Graphical Explanation

sorting array
Bubble sort process

Code Implementation

Complexity

Time: Best O(n), Average O(n²), Worst O(n²)
Space: O(1)
n: the total number of elements in the input array

Pseudocode

n = len(array)
for i in range n:
for j in range(n - i - 1):
if array[j] > array[j+1]:
swap(array[j], array[j+1])

Golang

Python

--

--

Claire Lee
Claire Lee

No responses yet