Bubble sort is a sorting algorithm that is used to sort an array or list.
Description:
Bubble Sort is one of the easiest sorting algorithms among all other sorting algorithms. In this algorithm, one needs to repeatedly compare the elements one by one and swap the adjacent elements to bring them in the correct sorted order. If there are n number of elements within the array then each element will undergo n-1 comparisons. This way after comparing one element with other elements within the array, an element is placed at its place in the sorted list similar to a bubble rising up and moving. That is why this algorithm is known as Bubble Sort. The number of comparisons in this algorithm is more thus its complexity is more.
Procedure for Bubble Sort:
BubbleSort (arr):
n =len(arr)
For i=0 to n-1:
For j=1 to n-i-1:
If arr[i] > arr[j]:
Swap(arr[i],arr[j])
Example:
First Pass:
( 7 5 0 2 4 ) –> ( 5 7 0 2 4 ), The algorithm compares the first two elements, and swaps since 7 > 5.
( 5 7 0 2 4 ) –> ( 5 0 7 2 4 ), Swap since 7 > 0
( 5 0 7 2 4 ) –> ( 5 0 2 7 4 ), Swap since 7 > 2
( 5 0 2 7 4 ) –> ( 5 0 2 4 7 ), Swap since 7 > 4
Second Pass:
( 5 0 2 4 7 ) –> ( 0 5 2 4 7 ), Swap since 5 > 0
( 0 5 2 4 7 ) –> ( 0 2 5 4 7 ), Swap since 5 > 2
( 0 2 4 5 7 ) –> ( 0 2 4 5 7 ), No swap as the elements are already sorted
( 0 2 4 5 7 ) –> ( 0 2 4 5 7 ), No swap as the elements are already sorted
We can see that the array is already sorted, but our algorithm does not know this. The algorithm needs one complete pass without any swap to know if the array is sorted or not.
Third Pass:
( 0 2 4 5 7 ) –> ( 0 2 4 5 7 )
( 0 2 4 5 7 ) –> ( 0 2 4 5 7 )
( 0 2 4 5 7 ) –> ( 0 2 4 5 7 )
( 0 2 4 5 7 ) –> ( 0 2 4 5 7 )
Time Complexity: O(n^2)
Python code for bubble sort
Output:
Optimized Implementation:
The above function always runs O(n^2) time even though the array is sorted. We can prevent this by stopping the algorithm if inner loop didn’t cause any swap.
OPTIMIZED PYTHON CODE
Time Complexity: