Algorithm Steps
- Start from the first element in the array.
- Compare the current element with the next element.
- If the current element is greater than the next element, swap them.
- Move to the next element and repeat steps 2 and 3 for the entire array.
- After one complete pass, the largest element will be at the end.
- Repeat the process for the remaining unsorted elements (excluding the last sorted ones).
- Continue until the array is completely sorted.
Bubble Sort Program Code
def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n - i - 1):
# Swap if the element found is greater than the next element
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
if __name__ == '__main__':
arr = [6, 3, 8, 2, 7, 4]
bubble_sort(arr)
print("Sorted array is:", arr)
Detailed Step by Step Example
Let us take the followign array, and apply Bubble Sort algorithm to sort the array.
Pass 1
➜ Comparing 6
and 3
6
> 3
.
Swap 6
and 3
.
We need to arrange them in ascending order.
➜ Comparing 6
and 8
6
<= 8
.
No swap needed.
They are already in ascending order.
➜ Comparing 8
and 2
8
> 2
.
Swap 8
and 2
.
We need to arrange them in ascending order.
➜ Comparing 8
and 7
8
> 7
.
Swap 8
and 7
.
We need to arrange them in ascending order.
➜ Comparing 8
and 4
8
> 4
.
Swap 8
and 4
.
We need to arrange them in ascending order.
8 is now at its correct position.
Pass 2
➜ Comparing 3
and 6
3
<= 6
.
No swap needed.
They are already in ascending order.
➜ Comparing 6
and 2
6
> 2
.
Swap 6
and 2
.
We need to arrange them in ascending order.
➜ Comparing 6
and 7
6
<= 7
.
No swap needed.
They are already in ascending order.
➜ Comparing 7
and 4
7
> 4
.
Swap 7
and 4
.
We need to arrange them in ascending order.
7 is now at its correct position.
Pass 3
➜ Comparing 3
and 2
3
> 2
.
Swap 3
and 2
.
We need to arrange them in ascending order.
➜ Comparing 3
and 6
3
<= 6
.
No swap needed.
They are already in ascending order.
➜ Comparing 6
and 4
6
> 4
.
Swap 6
and 4
.
We need to arrange them in ascending order.
6 is now at its correct position.
Pass 4
➜ Comparing 2
and 3
2
<= 3
.
No swap needed.
They are already in ascending order.
➜ Comparing 3
and 4
3
<= 4
.
No swap needed.
They are already in ascending order.
4 is now at its correct position.
Pass 5
➜ Comparing 2
and 3
2
<= 3
.
No swap needed.
They are already in ascending order.
3 is now at its correct position.
Pass 6
2 is now at its correct position.
Array is fully sorted.