<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var mySort = function(arr) {
if(arr.length <= 1) {
return arr;
}
var p1 = Math.floor(arr.length / 2); /*p1为一个数组里选的基准*/
var p2 = arr.splice(p1, 1)[0]; /*取出基准对应数组中的元素*/
var left = []; /*左边的数组*/
var right = []; /*右边的数组*/
for(var i = 0; i < arr.length; i++) {
if(arr[i] <p2) {
left.push(arr[i]); /*放入left数组*/
} else {
right.push(arr[i]); /*放入right数组*/
}
}
return mySort(left).concat([p2], mySort(right)); /*把left数组+p2+right数组进行拼接*/
}
alert(mySort([2,1,4,6,7]));
</script>
</body>
</html>
网友评论