A stable quadratic sorting algorithms. [Best: O(n), Average: O(n2), Worst: O(n2), Space: O(1)]
Idea
The idea of the bubble sort is to iteratively step through the array, compare pairs of adjacent items and swap them if needed. The largest item will quickly “bubble” to the end during one iteration. In an optimized implementation, it only takes O(n) scans for an already sorted array of n items. However, the performance is very slow for average cases.
Implementation
Below is an optimized implementation of bubble sort in golang. Each iteration in outer loop will keep track of the large items those have been already in their final positions. So the next iteration will skip those items.
package sorting |
References: