冒泡排序是你们最熟悉的算法,也是最简单的排序算法,因其排序过程很象气泡逐渐向上漂浮而得名。为了更好的理解其基本的思想,毛三胖利用JQuery实现了冒泡排序的动画演示,并计划陆续实现其它排序算法的动画演示。现将冒泡排序JQuery实现的基本思路和代码分享以下:javascript
冒泡排序动画演示css
演示动画前30秒gif图,图片大小1.60M。html
由于JavaScript中并不存在相似sleep()
这样的函数,因此只能利用setInterval()
来实现动画效果。所以不能利用算法的双重循环实现方式,只能算法过程拟合到一个时间轴上来实现动画效果。java
<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>
每隔一秒执行一次协做,完成排序后清除interval
。jquery
function go() { //设置当前相比较两元素样式 setCss(); interval = setInterval(function () { //times趟数,达到数组长度-1,结束循环 if(times < count -1) { //交换函数,如必要实现两元素交换 var change = exchange(); //如不交换,指针向前 if (!change) { current++; next++; //内部循环次数逐渐减小 if (current == count - 1 - times) { times++; current = 0; next = 1; //保留每一趟的历史数据 drawData(); } setCss(); } } else { //排序完成,清理 $lis.removeClass("active"); clearInterval(interval); } },1000); }
交换的动态效果利用了github的JQuery的swap,地址:Github jquery.swap.js。git
源代码以下:github
(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 );
目前,只完成了冒泡排序和直接插入排序两个算法的动画演示,其它的慢慢来完成吧。要学习完整的源代码可直接源文获取。算法
冒泡排序动画数组
插入排序动画函数