Bubble Sort
Bubble Sort
DAA
What is Bubble sort
We take an unsorted array for our example. Bubble sort takes Ο(n 2) time so we're keeping
it short and precise.
Bubble sort starts with very first two elements, comparing them to check which one is
greater.
In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we
compare 33 with 27.
How Bubble Sort Works?...
We find that 27 is smaller than 33 and these two values must be swapped.
Next we compare 33 and 35. We find that both are in already sorted positions.
How Bubble Sort Works?...
We know then that 10 is smaller 35. Hence they are not sorted.
We swap these values. We find that we have reached the end of the array. After one
iteration, the array should look like this −
How Bubble Sort Works?...
To be precise, we are now showing how an array should look like after each iteration. After
the second iteration, it should look like this −
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that an array is completely sorted.
Algorithm
Time Complexity
Best O(n)
Worst O(n2)
Average O(n2)
Stability Yes
Complexity in Detail
Cycle Number of Comparisons
1st (n-1)
2nd (n-2)
3rd (n-3)
....... ......
last 1
Bubble sort has a time complexity of O(N2) which makes it very slow for large data sets.
Bubble sort is a comparison-based sorting algorithm, which means that it requires a
comparison operator to determine the relative order of elements in the input data set. It can
limit the efficiency of the algorithm in certain cases.