This is actually a very simple JS can be achieved, of course, the general situation is to take advantage of the For loop, from the first compared to the second, based on the size of the interaction position, the idea is very simple.
that is, the bubble sort in JS.
The bubble sort time complexity is O (n^2), with two advantages:
1. "Programming complexity" is very low, it is easy to write code;
2. Stability, where the relative order of the same elements in the original sequence is still maintained to the ordered sequence, and the heap sorting, fast ordering are not stable.
To realize the basic idea: The bubble sort is completed by N-1, the first sub-order from the 1th number to the number of n-i, if the number of I is greater than the next number (then ascending, small, descending) then two number of exchanges.
Implement your own code below:
<Scripttype= "Text/javascript"> functionMaopao (ARRA) {vartemp; for(varI=0; I<Arra.length;i++){ //compare how many times, starting from the first trip for(varJ=0; J<Arra.length-I-1; J++){ //How many times do you compare each trip? if(Arra[j]>arra[j+1]) {temp=Arra[j]; ARRA[J]=arra[j+1]; Arra[j+1]=temp; } } }; returnArra; } varArrry=[ -, -, the, -, to, -, the, -]; vars=Maopao (Arrry); Console.log (s);</Script>
Printed results: [17, 17, 24, 31, 50, 63, 85, 86].
The topic is far away, on the internet to read a short video, although said the code is not very concise, but also a way of thinking, as follows:
functionMax (A, b) {returnA>b?a:b; } console.log (Max (2, 3));//3 varFunc =Max; Console.log (func (5,7));//7 functionmax1 () {varMaxValue = Arguments[0]; for(varI=1; i<arguments.length; i++) {MaxValue=Max (maxvalue,arguments[i]); } returnMaxValue; } console.log (Max1 (1,2,100,300,-8,-20,150));// -
The bubble sort in JS and the largest number of numbers in an array