1 前言
冒泡排序是大家最熟悉的算法汹胃,也是最簡單的排序算法勋陪,因其排序過程很象氣泡逐漸向上漂浮而得名揩瞪。為了更好的理解其基本的思想疹鳄,毛三胖利用JQuery實現(xiàn)了冒泡排序的動畫演示,并計劃陸續(xù)實現(xiàn)其它排序算法的動畫演示∨÷裕現(xiàn)將冒泡排序JQuery實現(xiàn)的基本思路和代碼分享如下:
2 動畫演示
2.1 演示地址
2.2 30秒GIF
演示動畫前30秒gif圖,圖片大小1.60M瘪弓。
3 動畫設(shè)計及實現(xiàn)
因為JavaScript中并不存在類似sleep()
這樣的函數(shù)垫蛆,所以只能利用setInterval()
來實現(xiàn)動畫效果。因此不能利用算法的雙重循環(huán)實現(xiàn)方式,只能算法過程擬合到一個時間軸上來實現(xiàn)動畫效果袱饭。
3.1 Html代碼
<ul id="myList">
<li>97</li>
<li>72</li>
<li>68</li>
<li>29</li>
<li>51</li>
<li>45</li>
<li>88</li>
<li>32</li>
<li>41</li>
<li>12</li>
</ul>
3.2 核心JS代碼
每隔一秒執(zhí)行一次協(xié)作川无,完成排序后清除interval
。
function go() {
//設(shè)置當(dāng)前相比較兩元素樣式
setCss();
interval = setInterval(function () {
//times趟數(shù)虑乖,達(dá)到數(shù)組長度-1懦趋,結(jié)束循環(huán)
if(times < count -1) {
//交換函數(shù),如必要實現(xiàn)兩元素交換
var change = exchange();
//如不交換疹味,指針向前
if (!change) {
current++;
next++;
//內(nèi)部循環(huán)次數(shù)逐漸減少
if (current == count - 1 - times) {
times++;
current = 0;
next = 1;
//保留每一趟的歷史數(shù)據(jù)
drawData();
}
setCss();
}
} else {
//排序完成仅叫,清理
$lis.removeClass("active");
clearInterval(interval);
}
},1000);
}
3.3 交換動效
交換的動態(tài)效果利用了github的JQuery的swap,地址:Github jquery.swap.js糙捺。
源代碼如下:
(function( $ ) {
$.fn.swap = function(a, b) {
t = this
if(t.length == 1 && a.length == 1 && b == undefined ){
return _swap(t, a);
}else if(t.length > 1 && typeof(a) == "number" && typeof(b) == "number" ){
_swap(t[a], t[b])
return t;
}else{
$.error( 'Argument Error!' );
}
};
function _swap(a, b){
var from = $(a),
dest = $(b),
from_pos = from.offset(),
dest_pos = dest.offset(),
from_clone = from.clone(),
dest_clone = dest.clone(),
total_route_vertical = dest_pos.top + dest.height() - from_pos.top,
route_from_vertical = 0,
route_dest_vertical = 0,
total_route_horizontal = dest_pos.left + dest.width() - from_pos.left,
route_from_horizontal = 0,
route_dest_horizontal = 0
from.css("opacity", 0);
dest.css("opacity", 0);
from_clone.insertAfter(from).css({position: "absolute", width: from.outerWidth(), height: from.outerHeight()}).offset(from_pos).css("z-index", "999")
dest_clone.insertAfter(dest).css({position: "absolute", width: dest.outerWidth(), height: dest.outerHeight()}).offset(dest_pos).css("z-index", "999")
if(from_pos.top != dest_pos.top)
route_from_vertical = total_route_vertical - from.height()
route_dest_vertical = total_route_vertical - dest.height()
if(from_pos.left != dest_pos.left)
route_from_horizontal = total_route_horizontal - from.width()
route_dest_horizontal = total_route_horizontal - dest.width()
from_clone.animate({
top: "+=" + route_from_vertical + "px",
left: "+=" + route_from_horizontal + "px",
},
"slow",
function(){
dest.insertBefore(this).css("opacity", 1);
$(this).remove();
});
dest_clone.animate({
top: "-=" + route_dest_vertical + "px",
left: "-=" + route_dest_horizontal + "px"
},
"slow",
function(){
from.insertBefore(this).css("opacity", 1);
$(this).remove();
});
return from;
}
})( jQuery );
4 結(jié)語
目前诫咱,只完成了冒泡排序和直接插入排序兩個算法的動畫演示,其它的慢慢來完成吧洪灯。要學(xué)習(xí)完整的源代碼可直接源文獲取坎缭。