js中两种实现排序的方法
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width; initial-scale=1.0; minimum-scale=1.0; maximum-scale=2.0" />
<title>冒泡排序-叶子制作</title>
<meta name="description" content="冒泡排序" />
<meta name="keywords" content="叶子" />
<style>
body{width:500px;margin:50px auto;}
span{display:inline-block;margin-bottom:20px;}
</style>
</head>
<body>
原数组:<span id="beforAry">100,12,3,4,5,6,2</span><br/>
排序之后的数组:<span id="afterAry"></span>
</body>
<script type="text/javascript">
/*方法一:
var beforeTxt = document.getElementById("beforAry").innerHTML;
var afterTxt = document.getElementById("afterAry");
var myAryTxt = beforeTxt.split(",");
var copeAry = myAryTxt.concat();
var newAry = copeAry.sort(function(a,b){
return a-b;
});
afterTxt.innerHTML = newAry;
//注意:该处排序并不是数字的排序,而是字符串的排序
//该方法较为简单,不做过多解释;
*/
/*方法二:
*思想
* 每轮将最大的放在后面,所以n个数比较n-1轮(也就是将n-1个最大数放在后面)就可以了 --i从0开始;
* 每轮比较多少次,不用跟自己比,最多n-1次;
* i=0, n-1-0 (--0将放到后面的除去)
* i=1, n-1-1
* i=2, n-1-2
* ...
* i=i, n-1-i
*/
var beforeTxt = document.getElementById("beforAry").innerHTML; //获取想要排序的字符串数字;
var afterTxt = document.getElementById("afterAry"); //获取想要将排好的数字放置的位置;
var myAryTxt = beforeTxt.split(","); //将获取的字符串进行分割;
var myAry1 = []; //声明一个空数组(为放置得到的数组做准备)
for(var i=0;i<myAryTxt.length;i++){ //利用循环将分割的分别获取到;
var myAry = Number(myAryTxt[i]); //将获取的每个字符数字都转化成纯数字;
myAry1.push(myAry); //将或有转化的数字当做数组元素存储;
}
var copeAry = myAry1.concat(); //复制一个数组;
function sortAry(ary){ //指定函数
for(var i=0;i<ary.length-1;i++){ //i是控制轮数的
for(var j=0;j<ary.length-1-i;j++){ //j控制每轮比较多少次;
if(ary[j]>ary[j+1]){ //如果当前的数字小于下一个,则调换位置;
var temp = null;
temp = ary[j];
ary[j] = ary[j+1];
ary[j+1] = temp;
}
}
}
return ary; //将排好序的数组返回;
}
var newAry = sortAry(copeAry); //执行函数
afterTxt.innerHTML = newAry; //将得到的数组放到指定位置;
</script>
</body>
</html>