Bubble Sort Algorithm Visualization

Source: Internet
Author: User
Tags sleep function

In the task list of the Baidu front-end Technical College There is a task that requires JavaScript to achieve a visual sorting algorithm, it is interesting to study a little bit, would like to achieve bubble sorting algorithm and fast sorting algorithm visualization, But the quick sort is a bit difficult to visualize, so it's time to give up.

Bubble Sort Principle

Bubble sort we should all be strangers, right? A very simple two for loop can be implemented, the basic principle is: in the beginning, compared to the first second number, if the first number is larger than the second number of the exchange of the two positions, in the comparison of the second and third number, the same if the second number than the third number, then the exchange of two positions, so repeat, So you can filter out the largest number in a trip and put it in the final position, and because a for loop can only pick one of the largest numbers, and we need to choose the second and third largest ... To the smallest number, so you need to add a for loop to achieve our goal. The JavaScript implementation is:

/*Bubble Sort*/functionBubblesort (arr) {if(arr.length<=1){        returnarr;    }; varTemp=0;  for(vari=0; i<arr.length; i++){         for(varj=0; j<arr.length-i-1; J + +){            if(arr[j]>arr[j+1]) {temp=Arr[j]; ARR[J]=arr[j+1]; Arr[j+1]=temp;        };    };    }; returnarr;} ;

The principle of visualization

The next step is to visualize the process of sequencing. We can implement it in two ways:

1 after each step of sequencing, we let the program pause for a while (JavaScript does not have a sleep function, we need to implement it ourselves), so that, in our opinion, the process of sorting is done step-by-step, it will not be the end of the order of the moment.

2 We can save the array after each order by maintaining an array, and after the sorting algorithm is finished, we then draw each of the saved arrays sequentially. That's the way I'm doing here.

var snapshots=[]; Snapshot collection
var timer=null; Timing
var arr=[50,21,5,89,13,35,69,44,60,15,51,80,55,71]; Sort arrays
/*Bubble Sort*/functionBubblesort (arr) {if(arr.length<=1){ returnarr; }; varTemp=0; for(vari=0; i<arr.length; i++){ for(varj=0; j<arr.length-i-1; J + +){ if(arr[j]>arr[j+1]) {temp=Arr[j]; ARR[J]=arr[j+1]; Arr[j+1]=temp; Snapshots.push (Json.parse (json.stringify (arr))); //<=Record the snapshot }; }; }; returnarr;};
Array.prototype.bubblesort=function () {
Return Bubblesort (this);

We set up a snapshots array variable to record the snapshot of the array after each order, and after the sort is finished, we can get a snapshot of the array that records the complete sorting process, and we then draw the snapshots at a certain interval, The visualization of the sequencing process can be achieved.

/*Drawing*/functionpainting () {varContainer=document.getelementbyid ("Container"); varBars=[].slice.call (Document.queryselectorall (". Bar"));//converts a collection of all bar elements to an array object     for(vari=0;i<arr.length;i++){        if(bars.length!=arr.length) {            varBar=document.createelement ("div"); Bar.classname= "Bar";        Container.appendchild (bar); }Else{             Break;//stop creating bar elements when the number of bar equals the length of the array        };    }; varSnapshot=snapshots.shift () | | [];//Take out the first record in the array of snapshot recordsconsole.log (snapshot); if(snapshot.length!=0){         for(vari=0; i<bars.length; i++) {bars[i].innerhtml=Snapshot[i]; Bars[i].style.height=snapshot[i]*5+ "px"; Bars[i].style.left= (i+1) *50+ "px";    }; }Else{clearinterval (timer); //Draw End        return; };};                                                Arr.bubblesort (); //SortTimer=setinterval (painting,200);//timed Drawing

Enclosed Demo Address: http://jerellin.github.io/visualization.html


It looks cool, doesn't it? But the visual implementation of the fast line does not come out to make me feel very depressed ah, it seems that the foundation is still no need to continue efforts.

Bubble Sort Algorithm Visualization

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.