Introduction to Bubble Sort
The algorithm, as its name suggests, allows smaller elements to bubble up and out slowly. You end up with the smaller element first and the larger element second.
The idea of bubble sort algorithm
Loop through each element in the array, comparing the current element with the next one in turn, swapping if the order is wrong (positive or reverse) until no element is swapped, and the current element is compared.
If n elements are compared, a total of N-1 comparisons are required, and n-K comparisons are required when the KTH comparison is made. So the total number of comparisons is :(n-1)+(n-2)+… +1 = n times n minus 1 over 2, O(n^2)
Bubble sort diagram
Images from https://www.itcast.cn/news/20191120/14135329023.shtml
Before performing the algorithm
After the algorithm is executed
Implementation process
Code Implementation (JS)
var arr = [3.43.38.5.47.15.36.26.27.2.44.4.50.19.38]
function BubbleSort(arr) {
var n = arr.length
for (var i = 0; i < n; i++) {
for (var j = 0; j < n - i - 1; j++) {
if (arr[j + 1] < arr[j]) {
[arr[j + 1], arr[j]] = [arr[j], arr[j + 1]]
}
}
}
}
BubbleSort(arr)
console.log(arr) / / [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 38, 43, 44, 47, 50]
Copy the code
Classical sorting algorithm – Bubble sort (Javascript) article at the end of the B station VIDEO I recorded welcome one button three connect