<script type="text/javascript">
//冒泡排序
function bubbleSort(arr){
var i = j = 0;
for(i=1;i<arr.length;i++){
for(j=0;j<=arr.length-i;j++){
var temp = 0;
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
console.log(bubbleSort([{a:3},{a:2}]))
// 快速排序
function quickSort(arr){
//如果数组<=1,则直接返回
if(arr.length<=1){return arr;}
var pivotIndex=Math.floor(arr.length/2);
//找基准,并把基准从原数组删除
var pivot=arr.splice(pivotIndex,1)[0];
//定义左右数组
var left=[];
var right=[];
//比基准小的放在left,比基准大的放在right
for(var i=0;i<arr.length;i++){
if(arr[i]<=pivot){
left.push(arr[i]);
}
else{
right.push(arr[i]);
}
}
//递归
return quickSort(left).concat([pivot],quickSort(right));
}
console.log(quickSort([1,2,3,0]))
// 归并排序
function mergeSort(items) {
if (items.length < 2) {
return items;
}
var middle = Math.floor(items.length / 2),
left = items.slice(0, middle),
right = items.slice(middle),
params = merge(mergeSort(left), mergeSort(right));
params.unshift(0, items.length);
// 原来的items替换成排序后的params
items.splice.apply(items, params);
return items;
function merge(left, right) {
var result = [],
il = 0,
ir = 0;
while (il < left.length && ir < right.length) {
if (left[il] < right[ir]) {
result.push(left[il++]);
} else {
result.push(right[ir++]);
}
}
return result.concat(left.slice(il)) .concat(right.slice(ir));
}
}
var arr = [2, 1, 3, 12, 5, 66, 23, 87, 15, 32];
console.log(mergeSort(arr));
</script>