JavaScript array Sort---2 bubbles

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.