One of the simplest sorting algorithms bubble sort----JS implementation

Source: Internet
Author: User

1. Algorithm steps
    1. Compares the adjacent elements. If the first one is bigger than the second one, swap them both.

    2. Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. When this is done, the final element will be the maximum number.

    3. Repeat the above steps for all elements, except for the last one.

    4. Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.

2. Motion Diagram Demo

3. When is the fastest

When the input data is already in the positive order (it is already a positive order, I also want you to bubble sort what is the use of AH).

4. When is the slowest?

When the input data is reversed (write a for loop to reverse the output data is not OK, why do you bubble sort it, I am idle).

5. JavaScript Code Implementation
 function  Bubblesort (arr) {var len = arr.length; for (var i = 0; i < Len; i++) {for (var j = 0; j < len-1-i ; J + +) {if (Arr[j] > Arr[j+1]) {// Adjacent elements 22 contrast var temp = Arr[j+1]; //element Exchange Arr[j+1] = Arr[j]; arr[j] = temp;}} } return arr;            

One of the simplest sorting algorithms bubble sort----JS implementation

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: 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.