Bubble sort in JavaScript

Source: Internet
Author: User

the principle of bubble sort:

For example, there are five numbers 54321, to be arranged from small to large;

First of all compare the first 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, and then compare the second and third, exchange position,

Turn 43521, then the third and fourth, fourth and fifth, so one cycle down, and turn into a 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.

Example One:

Five numbers, at least four rounds of circulation. As for why to This.length-i, because the first

var array = [5, 4, 3, 2, 1];
var temp = 0;
for (var i = 0; i < array.length; i++) { for (var j = 0; j < array.length-i; j+ +) { if (Array[j] > array[j + 1]) { = array[j + 1]; + 1] = array[j]; = temp;}} } Console.log (array); [1,2,3,4,5]
Example Two:

sort a two-dimensional array given by a background, such as var array = [[4, ' DASD '],[5, ' dasd '],[1, ' dasd '],[2, ' DASD '],[3, ' dasd '],[13, ' dasd '],[23, ' DASD ']; Sorts from small to large based on the first ID value of each array.

var array = [[4, ' DASD '],[5, ' dasd '],[1, ' dasd '],[2, ' dasd '],[3, ' dasd '],[13, ' dasd '],[23, ' DASD ']; var temp = 0;  for (var i = 0; i < array.length; i++) {    for (var j = 0; J < array.length-i- 1; J + +) {        if (array[j][0] >= array[j + 1][0]            ) {= array[j + 1];            + 1] = array[j];             = temp;}}    } Console.log (Array)

Bubble sort in JavaScript

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.