JavaScript for bubbling sorting

Source: Internet
Author: User

Thought: Starting with the first element, comparing 22 adjacent elements in an array, placing the element with the smaller value in front, the larger value of the element in the back, a round comparison, a maximum number of sink becoming the last element in the array, and some smaller numbers floating in a position like bubbles. n number, after the n-1 round comparison completed sorting.

var arr=[5,0,-56,900,12];
VAR flag=false;//flag bit, used for control program comparison number, if ordered, this flag can reduce the number of comparisons
for (Var i=0;i<arr.length-1;i++) {//Large sort count (arr.length-1)
Document.writeln ("Loop <br/>");//used to view the number of comparisons
for (Var j=0;j<arr.length-1-i;j++) {//small sort
if (Arr[j]>arr[j+1]) {
Exchange
var temp=arr[j];
ARR[J]=ARR[J+1];
Arr[j+1]=temp;
flag=true;//swapped.
}
}
if (flag) {
Flag=false;
}else{
Break;//was already orderly, and withdrew
}
}
Iterating through the sorted array of outputs
for (Var i=0;i<arr.length;i++) {
Document.writeln (arr[i]+ "&nbsp;");
}

JavaScript for bubbling sorting

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.