Bubble Sort is a simple 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.
How it works:
Example:
Let's sort the array [5, 1, 4, 2, 8]
.
Iteration 1:
5
and 1
: Swap (1, 5, 4, 2, 8)5
and 4
: Swap (1, 4, 5, 2, 8)5
and 2
: Swap (1, 4, 2, 5, 8)5
and 8
: No swap (1, 4, 2, 5, 8)Iteration 2:
1
and 4
: No swap (1, 4, 2, 5, 8)4
and 2
: Swap (1, 2, 4, 5, 8)4
and 5
: No swap (1, 2, 4, 5, 8)5
and 8
: No swap (1, 2, 4, 5, 8)Iteration 3:
1
and 2
: No swap (1, 2, 4, 5, 8)2
and 4
: No swap (1, 2, 4, 5, 8)4
and 5
: No swap (1, 2, 4, 5, 8)5
and 8
: No swap (1, 2, 4, 5, 8)Since no swaps were made in Iteration 3, the array is sorted: [1, 2, 4, 5, 8]
.
Code Example:
for i in range(len(array) - 1):
for j in range(len(array) - i - 1):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
Complexity:
Advantages:
Disadvantages:
Conclusion:
Bubble Sort is a basic sorting algorithm that is easy to implement but inefficient for large datasets. While it may be useful for small arrays or educational purposes, more efficient algorithms like Merge Sort or Quick Sort are generally preferred for real-world applications.