Detailed description of the Javascript Bubble Sorting Algorithm and the javascript Bubble Sorting Algorithm

Source: Internet
Author: User

Detailed description of the Javascript Bubble Sorting Algorithm and the javascript Bubble Sorting Algorithm

Compares adjacent elements. If the first is bigger than the second, exchange the two of them.
Perform the same operation on each adjacent element, from the first to the last. At this point, the final element should be the largest number.
Repeat the preceding steps for all elements except the last one.
Continue to repeat the above steps for fewer and fewer elements until there is no need to compare them.

Copy codeThe Code is as follows:
Function sort (elements ){
For (var I = 0; I <elements. length-1; I ++ ){
For (var j = 0; j <elements. length-i-1; j ++ ){
If (elements [j]> elements [j + 1]) {
Var swap = elements [j];
Elements [j] = elements [j + 1];
Elements [j + 1] = swap;
}
}
}
}

Var elements = [3, 1, 5, 7, 2, 4, 9, 6, 10, 8];
Console. log ('before: '+ elements );
Sort (elements );
Console. log ('after: '+ elements );

 
Efficiency:

Time Complexity: Best: O (n), worst: O (n ^ 2), average: O (n ^ 2 ).

Space complexity: O (1 ).

Stability: stable.

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.