The bubble sort in JS and the largest number of numbers in an array

Source: Internet
Author: User

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

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.