var Numberarray = [3, 6, 2, 4, 1, 5, 13];
Implements the order of the size of the array, output [1,2,3,4,5,6,13]
var arr2 = Numberarray.sort (function (A, b) {
if (a > B) {
return 1;
} else if (a < b) {
return-1;
} else {
return 0;
}
});
Console.log (ARR2);//[1, 2, 3, 4, 5, 6, 13]
Because the sort () method of the array is sorted by string, we need to make a judgment. If the Var arr2=numberarray.sort () is used directly, then it will be the effect of [1,13,2,3,4,5,6];
It's much leaner than the previous code.
Outer loop control wheel number (number of elements minus one)
for (Var i=0;i<numberarray.length-1;i++) {
Switch in the open/close principle (default is on)
var bool = true;
Internal loop control Number (number of elements minus one)
for (Var j=0;j<numberarray.length-1-i;j++) {
Note: 1. How to compare? (two consecutive number comparisons) 2. When to swap positions. (large number of front)
What if the condition and the exchange element position are determined?
if (Numberarray[j] > numberarray[j+1]) {
Swap location
var temp = numberarray[j];
NUMBERARRAY[J] = numberarray[j+1];
NUMBERARRAY[J+1] = temp;
No students raise their hands. (no sort is finished)
bool = false;
}
}
The IF statement in the inner loop is not executed
if (bool) {
Break
}
}
Console.log (Numberarray);//[1, 2, 3, 4, 5, 6, 13];
Ultimate version: var arr2 = Numberarray.sort (function (A, b) {
return a-B;
});
Console.log (ARR2);//[1, 2, 3, 4, 5, 6, 13];
Array Tips sort ()