1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <Head>4 <MetaCharSet= "UTF-8">5 <title>JavaScript array Bubble Sorting method</title>6 </Head>7 <Body>8 <Script>9 varArray= [7, 9, A, One, A, -, 5, 4, 3, 2, 1];Ten varTemp= 0; One for (varI= 0; I<array.length; I++) { A for (varJ= 0; J<Array.Length-i; J++) { - if(Array[j]>array[j+ 1]) { - Temp=array[j+ 1]; the array[j+ 1] =Array[j]; - Array[j]=temp; - } - } + } - Console.log (array); + </Script> A </Body> at </HTML> - <!--The principle of bubble sorting is this, for example, there are five numbers 54321, to be arranged from small to large; - first compare the top 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, then compare the second and third, the exchange position, into 43521, then the third and fourth, fourth and fifth, So one cycle down and into 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. Like this example, five numbers, at least four rounds of circulation. As for why to This.length-i, because the first comparison of five numbers, the second as long as the comparison of the first four on the line, the fifth is definitely the largest one. -
The 12th line of
J < Array.length-i
Can not subtract I but in order to be code readable, logical, preferably minus 1
JavaScript array Sort---2 bubbles