Bubble Sort Algorithm
Algorithm Summary
Bubble Sort is a simple comparison-based 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.
Key Features
In-place, meaning it doesn't require extra space for sorting.
Stable, meaning the relative order of equal elements is preserved.
Algorithm Steps
Start from the beginning of the list.
Compare adjacent elements and swap them if they are in the wrong order.
Repeat this process for each pair of adjacent elements in the list until no swaps are needed.
Complexity Analysis
Time Complexity
Best-case: O(n) when the list is already sorted.
Average-case and worst-case: O(n^2) comparisons and swaps, where n is the number of elements in the list.
Bubble Sort is not suitable for large datasets due to its quadratic time complexity. It is often used as a teaching tool due to its simplicity, but it's rarely used in practice for real-world applications where efficiency is critical.
Space Complexity
In all cases, space complexity is O(1) because Bubble Sort is an in-place sorting algorithm.
Implementation
We implement bubble sort as a finite state machine with the following states:
Pass: compare adjacent elements and rebuild list in acc
After a pass, reverse the accumulator to restore order
Return the sorted array
Interface
Take a list, a, that's just a list of numbers
a<[u64]>:=[We can run the bubble sort algorithm on it: