Bubble Sorting
Explanation of bubble Sorting
Naive Version
Image that a fish at the bottom of water tank blows bubbles, the bubbles will rise in the tank until they reach the water surface. That is similar to how bubble sorting algorithm works.
To start with, assuming we have this set of numbers and we want to sort it in inscending order:
1 |
|
1 |
|
Then we compare each two number next to each other from left to right, if the one on the left is larger than the right one, swap them:
If we continue to do it n(the length of set) times, the set is sorted in order.
Improvement
After 1 large round, we can see that we have the largest number at the most right place. If we keep doing swaps, at n round, we will have the nst largest number set on its final position.
In this case, each large round we only need to compare the first n-m(the large round number) numbers instead of all n numbers.
Pros and Cons of bubble sorting
Pros
- The space complexity is low.
- The algorithm is stable which means that the positions of two equal numbers won’t change after the sorting. This property is quite useful when sorting complex structured data.
Cons
- The time complexity is high which is O(n2).
Implementation
Python
1 |
|
Java
1 |
|
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!