Bubble Sort in Python
A Bubble sort is an easy algorithm among the various sorting algorithms. We learn it as a first sorting algorithm. It is easy to learn and highly intuitive. It can be easy to implement into the code, which is much beneficial for beginner software developers. But it is the worst algorithm for sorting the elements in every except because it checks every time the array is sorted or not.
Let's understand the concepts of the bubble sort.
Program
Output:
The unsorted list is: [5, 3, 8, 6, 7, 2] The sorted list is: [2, 3, 5, 6, 7, 8]
Explanation:
In the above code, we have defined a bubble_sort() function which takes list1 as an argument.
- Inside the function, we have defined two for loop - first for loop iterates the complete list and the second for loop iterates the list and the compare the two elements in every outer loop iterations.
- The for loop will be terminated when it reaches at the end.
- We have defined the condition in the inner for loop; if a first index value is greater than the second index value, swap their positions with each other.
- We called the function and passed a list; it iterated and returned the sorted list.
Example -
We are creating a list of element, which stores the integer numbers
list1 = [5, 3, 8, 6, 7, 2]
Here the algorithm sort the elements -
First iteration
It compares the first two elements and here 5>3 then swap with each other. Now we get new list is -
[3, 5, 8, 6, 7, 2]
In second comparison, 5 < 8 then swapping happen -
[3, 5, 8, 6, 7, 2]
In third comparison, 8>6 then swap -
[3, 5, 6, 8, 7, 2]
In fourth comparison, 8>7 then swap -
[3, 5, 6, 7, 8, 2]
In fifth comparison, 8>2 then swap-
[3, 5, 6, 7, 2, 8]
Here the first iteration is complete and we get the largest element at the end. Now we need to the len(list1) - 1