It will take about 3 minutes to finish reading this article.
Bubble Sort
1. Description
Bubble sort is a simple sorting algorithm that repeatedly traverses the array to be sorted, compares adjacent elements, and swaps them if necessary until the entire array is sorted in ascending or descending order. The name of the algorithm comes from the fact that larger elements “bubble” to the end of the array during each comparison.
2. Algorithm complexity
Time Average Complexity: O(N^2)
Worst Complexity: O(N^2)
Best Complexity: O(N)
Space Complexity: O(1)
Stable Or Not: Yes
3. Implementation
1 | func bubbleSorting(_ sourceArray: [Int]) -> [Int] { |
Execute as follows:
1 | let sourceArray = [9, 4, 7, 2, 1, 8, 0, 3, 6, 5] |
Template code as follows:
1 | func bubbleSort<T: Comparable>(_ array: [T]) -> [T] { |