the principle of bubble sort:
For example, there are five numbers 54321, to be arranged from small to large;
First of all compare the first two, that is 5 and 4, if the first is less than the second, do not do the operation, if the first is greater than the second, then the position of the exchange of the two, that becomes 45321, and then compare the second and third, exchange position,
Turn 43521, then the third and fourth, fourth and fifth, so one cycle down, and turn into a 43215.
So, the effect of a layer of loops is to pick out the largest number 5, bubbling to the last side. But also to pick out the second largest, the third largest number, and so on. So a layer of circulation is not enough, it must be one more layer.
Example One:
Five numbers, at least four rounds of circulation. As for why to This.length-i, because the first
var array = [5, 4, 3, 2, 1];
var temp = 0;
for (var i = 0; i < array.length; i++) { for (var j = 0; j < array.length-i; j+ +) { if (Array[j] > array[j + 1]) { = array[j + 1]; + 1] = array[j]; = temp;}} } Console.log (array); [1,2,3,4,5]
Example Two:
sort a two-dimensional array given by a background, such as var array = [[4, ' DASD '],[5, ' dasd '],[1, ' dasd '],[2, ' DASD '],[3, ' dasd '],[13, ' dasd '],[23, ' DASD ']; Sorts from small to large based on the first ID value of each array.
var array = [[4, ' DASD '],[5, ' dasd '],[1, ' dasd '],[2, ' dasd '],[3, ' dasd '],[13, ' dasd '],[23, ' DASD ']; var temp = 0; for (var i = 0; i < array.length; i++) { for (var j = 0; J < array.length-i- 1; J + +) { if (array[j][0] >= array[j + 1][0] ) {= array[j + 1]; + 1] = array[j]; = temp;}} } Console.log (Array)
Bubble sort in JavaScript