JavaScript模拟冒泡排序
JavaScript模拟冒泡排序排序过程,冒泡排序模拟过程效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript模拟冒泡排序</title> <style type="text/css"> div div{width: 10px;background-color: red;display: inline-block;margin-right: 1px;text-align: center;line-height: 30px;} #show {width: 500px;height: 300px;margin-left: auto;margin-right: auto;margin-top: 50px;} </style> </head> <body> <div id="dvBtn"><input type="button" value="冒泡升序" onclick="sort(document.getElementById('show').getElementsByTagName('div'),true)"> <input type="button" value="冒泡降序" onclick="sort(document.getElementById('show').getElementsByTagName('div'),false)"> <input type="button" value="打乱顺序" onclick="sortRnd()"></div> <div id="show"> <div style="height: 80px; background-color: red;"></div> <div style="height: 100px; background-color: red;"></div> <div style="height: 40px; background-color: red;"></div> <div style="height: 60px; background-color: red;"></div> <div style="height: 120px; background-color: red;"></div> <div style="height: 20px;"></div> <div style="height: 200px; background-color: red;"></div> </div> <script type="text/javascript"> function sortRnd() {//打乱排序 var show = document.getElementById('show'), divs = show.getElementsByTagName('div'), l = divs.length; for (var i = 0; i < l; i++) show.appendChild(divs[Math.round(Math.random() * l)]); } function disabledButton(disabled) { var btn = document.getElementById('dvBtn').getElementsByTagName('input'); for (var i = 0; i < btn.length; i++) btn[i].disabled = disabled } function plusIJ(arr, isAsc) { arr.j++; if (arr.j < arr.length - 1 - arr.i) sort(arr, isAsc, true);//继续冒泡 else { arr.i++; arr.j = 0; if (arr.i < arr.length) sort(arr, isAsc, true);//继续冒泡 else { alert('排序结束!') arr.i = arr.j = undefined; disabledButton(false); } } } //冒泡排序 从小到大 function sort(arr, isAsc, isFor) { if (!isFor) { arr.i = arr.j = 0; disabledButton(true);} if ((isAsc && parseInt(arr[arr.j].style.height) > parseInt(arr[arr.j + 1].style.height)) || (!isAsc && parseInt(arr[arr.j].style.height) < parseInt(arr[arr.j + 1].style.height))) { arr[arr.j].style.backgroundColor = "#999"; arr[arr.j + 1].style.backgroundColor = "#999"; setTimeout(function () { var c = arr[arr.j + (isAsc ? 0 : 1)].style.height; arr[arr.j + (isAsc ? 0 : 1)].style.height = arr[arr.j + (isAsc ? 1 : 0)].style.height; arr[arr.j + (isAsc ? 1 : 0)].style.height = c; arr[arr.j].style.backgroundColor = arr[arr.j + 1].style.backgroundColor = "red"; plusIJ(arr, isAsc); }, 1000);//1s后交换 } else plusIJ(arr, isAsc); } </script> </body> </html>
加支付宝好友偷能量挖...
原创文章,转载请注明出处:JavaScript模拟冒泡排序