Bubble Sort is a basic sorting algorithm that orders elements by repeatedly comparing and swapping adjacent pairs that are out of order. After each full pass through the list, the largest remaining element “bubbles up” to its correct position at the end. The process continues until the list is sorted.
function bubble_sort(A):
n = length(A)
repeat
swapped = false
for i from 0 to n - 2:
if A[i] > A[i + 1]:
swap(A[i], A[i + 1])
swapped = true
n = n - 1 # largest element is now at position n
until not swapped
return A
Given A = [5, 1, 4, 2, 8]