Js sorting animation simulates Bubble Sorting

Source: Internet
Author: User

In some scenarios, the queue is indeed like a vanguard, which can bring good results. For example, it can be used with a timer to simulate the time difference effect.
Copy codeThe Code is as follows:
Function createDq (){
Var dq = [], size = 0;
Return {
SetDq: function (queue ){
Dq = queue;
Size = queue. length;
},
Queue: function (fn ){
Size ++;
Dq. push (fn );
},
Dqueue: function (){
Size --;
Return dq. shift ();
},
Run: function (fn ){
Var me = this, timer;
Timer = setInterval (function (){
If (size <= 1 ){
ClearInterval (timer );
}
Fn. call (null, me. dqueue ());
}, 30 );
}
}
}

The above is a simple implementation. In different scenarios, you can make some appropriate changes to adapt to local conditions.
The following is an animation simulating Bubble sorting. It seems pretty good to try to use the observer mode with a little bit of it.
Copy codeThe Code is as follows:
Function bubble (){
Var obs = [];
Function compare (x, y ){
Return x. w-y. w;
}
Function swap (a, I, j ){
Var t = a [I]; a [I] = a [j]; a [j] = t;
}
Function proxy (a, I, j ){
Y (a [I]. id + "-" + a [j]. id );
Swap. apply (null, arguments );
}
Function notify (arg ){
Obs [0]. m. call (obs [0], arg );
}
Return {
AddOb: function (ob ){
Obs. push (ob );
},
Sort: function (arr ){
Var len = arr. length;
For (var x = 1; x <len; x ++ ){
For (var y = 0; y <len-x; y ++ ){
If (compare (arr [y], arr [y + 1])> 0 ){
Proxy (arr, y, y + 1 );
}
}
}
}
}
}

<! DOCTYPE html "> <ptml> <style> </style> <ul id =" mop "> </ul> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

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.