⬅ Previous Topic
Heaps Technique in DSANext Topic ⮕
Selection Sort⬅ Previous Topic
Heaps Technique in DSANext Topic ⮕
Selection SortTopic Contents
Given an array of integers, your task is to sort the array in ascending order using the Bubble Sort algorithm.
Bubble Sort works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. The largest unsorted element 'bubbles up' to its correct position after each pass.
Your goal is to return the sorted array after all necessary passes are completed.
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)
Let us take the followign array, and apply Bubble Sort algorithm to sort the array.
➜ 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.
➜ 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.
➜ 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.
➜ 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.
➜ Comparing 2
and 3
2
<= 3
.
No swap needed.
They are already in ascending order.
3 is now at its correct position.
2 is now at its correct position.
Array is fully sorted.
⬅ Previous Topic
Heaps Technique in DSANext Topic ⮕
Selection SortYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.