Enter an array separated by commas as : 16,15,15,10,1 or just press the hand icon to generate a random array then press enter or Sort button. Sorting will start and you can watch each pass as it gets sorted. When it shows green it means the two of them are being compared when red shows, it means the left number is greater than right number so it needs swapping The blue color means the number is at its correct position and thus sorted it will continue to check other numbers until it reaches end.
Bubble sort is one of the simplest sorting algorithms, often introduced in computer science education. It was first documented in the 1950s and has been widely used in programming for educational purposes due to its straightforward concept.
O(n) - When the array is already sorted.O(n2) - Quadratic complexity for
average
cases.
O(n2) - When the array is sorted in
reverse
order.
Space Complexity: O(1) - It is an in-place sorting algorithm
requiring
a constant amount of additional space.
function bubbleSort(arr):
n = length(arr)
for i from 0 to n-1:
for j from 0 to n-i-1:
if arr[j] > arr[j + 1]:
// swap arr[j] and arr[j + 1]
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
return arr
Bubble sort is an easy-to-understand sorting algorithm that works by repeatedly swapping adjacent
elements. While it is inefficient for large datasets with its O(n2)
worst-case
complexity, its simplicity makes it suitable for educational purposes.
Imagine the array as a vertical column where the largest numbers "bubble up" to the top, pass by pass. The core idea is a series of passes over the array:
arr[0] and
arr[1].arr[1] and
arr[2].n passes (or until no
swaps occur), the array is fully sorted.In the visualization above, green highlights the pair currently being compared, red means a swap is needed, and blue marks elements locked in their final sorted position.
Bubble sort is rarely the best choice for production data, but it shines in a few specific situations:
O(n) performance.