By Harsh Tanwar
Bubble sort is a simple sorting algorithm that repeatedly steps through the array to be sorted, it compares each pair of adjacent items and swaps them if they are in the wrong order.
We pass through the array until there is no element to swap and hence the array is sorted.
The algorithm is simple but it is too slow and so it is not as efficient as some other algorithms like insertion sort.
How does it work:
step 1: We compare the jth and the (j+1)th element, if the jth element is bigger we swap them as here we always need (j+1)th element to be bigger.
step 2: then we keep repeating this process until the end of the array. and till the end of this first pass, our last element is the biggest one in the array.
step 3: we keep repeating this process till we don't reach the case where no swap is needed.
step 4:the array we get after the last pass is our sorted array.
[1, 3, 4, 5, 7, 8, 9] //sorted array
The time complexity of Bubble Sort is O(n2)
Submitted by Harsh Tanwar (harshtanwar)
Download packets of source code on Coders Packet