Bubble Sort Algorithm
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²)).
Table of Contents· How Does Bubble Sort Algorithm Work?
· Graphical Explanation
· Code Implementation
∘ Complexity
∘ Pseudocode
∘ Golang
∘ Python
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
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
You can access the source code here.
Other sorting algorithms: