Bubble sort program in Python
How Bubble sort works ?
Bubble sort is a simple sorting algorithm that compares the adjacent numbers in an array and swaps them if they are in the wrong order.
It is also referred to as a sinking sort.
In this program, we will learn to implement bubble sort in an array in order to sort the array in increasing order. Although the algorithm is simple but it is slow and impractical for some problems when it is compared to insertion sort.
- An array[arr] is initialized.
- Length of the array is stored in a variable n.
- For each value in array, a loop is generated.
- For each value of the iteration from (3) a loop is generated excluding these many items because they are sorted towards the end.
- Swap if a bigger number is encountered using a temporary variable “temp”.
- Loop ends 4.
- Loop ends 3.
- Print the sorted array, which is in place of the original array now.
Code for bubble sort python:
for i in range(n):
for j in range(0,n-i-1):
print("Sorted Array : ", arr )
Sorted Array : [1, 2, 3, 5, 6, 9]