Bubble sort in JavaScript

Source: Internet
Author: User

Bubble sort: The elements in an array are arranged in order from large to small or from small to large.

var array=[9,8,7,6,5,4,3,2,1];

First round comparison: 8,7,6,5,4,3,2,1,9 exchanged 8 times i=0 j=array.length-1-i

Second round comparison: 7,6,5,4,3,2,1,8,9 exchanged 7 times I=1 J=array.length-1-i

Third round comparison: 6,5,4,3,2,1,7,8,9 exchanged 6 times i=2 J=array.length-1-i

Fourth round comparison: 5,4,3,2,1,6,7,8,9 exchanged 5 times i=3 J=array.length-1-i

Fifth round comparison: 4,3,2,1,5,6,7,8,9 exchanged 4 times i=4 j=array.length-1-i

Sixth round comparison: 3,2,1,4,5,6,7,8,9 exchanged 3 times i=5 j=array.length-1-i

Seventh round comparison: 2,1,3,4,5,6,7,8,9 exchanged 2 times i=6 j=array.length-1-i

Eighth round comparison: 1,2,3,4,5,6,7,8,9 exchanged 1 times i=7 j=array.length-1-i

Code implementation:

var temp;
var array=[9,8,7,6,5,4,3,2,1];
External loop control Wheel number
For (Var i=0;i<array.length-1;i++) {
Internal loop control comparison times
For (Var j=0;j<array.length-1-i;j++) {
if (array[j]>array[j+1]) {
Swap two variables
Temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
Console.log (array);

Code optimization:
var  temp,bool,m=0;
var array=[9,8,7,6,5,4,3,2,1];
For (Var i=0;i<array.length-1;i++) {
//switch in the open/closed principle
bool = true;
For (Var j=0;j<array.length-1-i;j++) {
if (array[j]>array[j+1]) {
//exchange of two variables
Temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
bool=false;//Turn off the switch
}
}
if the inner loop is not executed (switch off, execute the following statement);
if (bool) {
Break ;
}
m++;
}
Console.log (array+ ", compare" +m+ "wheel");
Note: Compare the number of wheels best for 0 rounds, the worst is 8 rounds

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.