1.冒泡排序(思想:每一次的循环,都是从最后一位开始,和前一位比较,如果小于前一位,就交换位置,直到不能交换为止。最慢但最易实现)
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>排序</title> </head> <body> <button id="pro">生成随机数组:</button> <p id="arr"></p> <button id="do">进行冒泡排序:</button> <p id="result"></p> <script type="text/javascript"> function order(a){ var result = ""; for (var i = 0; i < a.length; i++) { for (var j = a.length; j > 0; j--) { if (a[j] < a[j - 1]) { var temp = a[j - 1]; a[j - 1] = a[j]; a[j] = temp; } } result += "第" + (i + 1) + "次循环,结果为:"; for (var k = 0; k < a.length; k++) { result += a[k] + ","; } result += "<br />"; } return result; } var opro = document.getElementById("pro"); var oarr = document.getElementById("arr"); var arr = []; opro.onclick = function(){ for (var i = 0; i < 5; i++) { arr[i] = Math.ceil(Math.random()*(100 - 0)+0) }; oarr.innerHTML = arr; } var odo = document.getElementById("do"); odo.onclick = function(){ var oresult = document.getElementById("result"); oresult.innerHTML = order(arr); } </script> </body> </html>
2.选择排序(思想:每一次的循环都是从第一位开始,后以后的每一位比较,比较完所有的位数后,将最小的数放在第一位)
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>排序</title> </head> <body> <button id="pro">生成随机数组:</button> <p id="arr"></p> <button id="do">进行选择排序:</button> <p id="result"></p> <script type="text/javascript"> function order(a){ var result = ""; var min; for (var i = 0; i < a.length-1; i++) { min = i; for (var j = i+1; j < a.length; j++) { if (a[min] > a[j]) { min = j; } } if (min != i) { var temp = a[min]; a[min] = a[i]; a[i] = temp; } result += "第" + (i + 1) + "次循环,结果为:"; for (var k = 0; k < a.length; k++) { result += a[k] + ","; } result += "<br />"; } return result; } var opro = document.getElementById("pro"); var oarr = document.getElementById("arr"); var arr = []; opro.onclick = function(){ for (var i = 0; i < 5; i++) { arr[i] = Math.ceil(Math.random()*(100 - 0)+0) }; oarr.innerHTML = arr; } var odo = document.getElementById("do"); odo.onclick = function(){ var oresult = document.getElementById("result"); oresult.innerHTML = order(arr); } </script> </body>
3.插入排序(思想:外循环用来移动数组,内循环用来对外循环中选中的元素以及它后面的元素进行比较)
function order(a){ var result = ""; for (var i = 1; i < a.length; i++) { var temp=a[i]; for(var j=i-1;j>=0&&temp<a[j];j--){ a[j+1]=a[j]; //将大于temp的值整体后移一个单位 } a[j+1]=temp; result += "第" + (i + 1) + "次循环,结果为:"; for (var k = 0; k < a.length; k++) { result += a[k] + ","; } result += "<br />"; } return result; }
4.快速排序(思想:选择一个基准,小于它的数都在左边,大于他的数都在右边,循环调用函数,实现排序)
function order(arr) { var result = ""; if (arr.length <= 1) { return arr; } var pivotIndex = Math.floor(arr.length / 2); var pivot = arr.splice(pivotIndex, 1)[0]; var left = []; var right = []; for (var i = 0; i < arr.length; i++){ if (arr[i] < pivot) { left.push(arr[i]); } else { right.push(arr[i]); } } result = order(left).concat([pivot], order(right)); return result; };