Bubble sort is a sorting algorithm to sort a list into ascending (or descending) order. This is the easiest sorting algorithm but it is not very efficient. It can be used on small input sizes but not time efficient for lists or arrays with larger length. Its time complexity is O(n^2). However, this is an in-place sorting algorithm, which means it doesn’t use any extra space. Thus, its efficient in terms of space complexity. However, it is not used much since there are better sorting algorithms than bubble sort.
In bubble sort, two for loops are used. The outer for loop iterates over the list. The inner for loop also iterates over the list for all the outer loop iterations.
The main operation in Bubble sort is to compare two consecutive elements. If the first element is greater than the next element, then swap both, so that the smaller element comes ahead and the greater element goes back.In one iteration of outer loop, the greatest element of the list goes at the last index. In the second iteration of the outer loop, the second largest element of the list goes at the second last index and so on. Therefore, we get the sorted list at the end of all the iterations.
We can better understand with the help of an example.
We are required to sort the following list.
5>2, therefore swap both
5>1, therefore swap both
5>3, therefore swap both
5>4, therefore swap both
(The largest element 5 has reached at the last index after the first outer iteration)
2>1, therefore swap
No swapping required
No swapping required
As we can see the list is sorted in the 2nd outer iteration itself. But the outer loop will iterate 3 more times with no further swap operations. Hence,only 2 iterations are shown in the example. Sometimes, the list can be sorted in the first iteration itself. Sometimes, the list might be sorted in the last iteration. Thus, the outer loop will always iterate n times.
def bubble_sort(arr): for i in range(len(arr)): for j in range(len(arr)-1): if(arr[j]>arr[j+1]): temp=arr[j] arr[j]=arr[j+1] arr[j+1]=temp return arr array=[2,3,1,5,4] print(bubble_sort(array))
[1, 2, 3, 4, 5]