JS实现经典排序算法

/** 选择排序 */
function selectionSort(arr) {
    var minIndex,temp;
    for(var i=0;i<arr.length;i++){
        minIndex = i;
        for(var j=i+1;j<arr.length;j++){
            /** 寻找最小的数 */
            if(arr[j]<arr[minIndex]){
                minIndex = j;
            }
        }
        temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }
    return arr;
}
var arr = [3,44,38,5,47,15,36,26,27,1,46,4];
console.log("选择排序:"+selectionSort(arr));

function bubbleSort(arr) {
    var len = arr.length;
    var temp,min;
    for(var i=1;i<len;i++){
        if(arr[i]<arr[i-1]){
            temp = arr[i];
            arr[i] = arr[i-1];
            arr[i-1] = temp;
        }
    }
    return arr;
}
console.log("冒泡排序:"+bubbleSort(arr));

function insertionSort(arr) {
    var len = arr.length;
    var current,preIndex;
    for(var i=1;i<len;i++){
        current = arr[i];
        preIndex = i-1;
        while (preIndex>=0 && arr[preIndex]>current){
            arr[preIndex+1] = arr[preIndex];
            preIndex--;
        }
        arr[preIndex+1] = current;

    }
    return arr;
}
console.log("插入排序:"+insertionSort(arr));

function shellSort(arr) {
    var len = arr.length;
    var d = Math.floor(len/2);

    while(d>0){
        var current,preIndex;
        for(var j=0;j<len;j++){
            for(var i=j+d;i<len;i+=d){
                current = arr[i];
                preIndex = i-d;
                while (preIndex>=0 && arr[preIndex]>current){
                    arr[preIndex+d] = arr[preIndex];
                    preIndex -= d;
                }
                arr[preIndex+d] = current;
            }
        }

        d = Math.floor(d/2);
    }
    return arr;

}
console.log("希尔排序:"+shellSort(arr));

function quickSort(arr) {
    if(arr.length<=1) return arr;
    var pivotIndex = Math.floor(arr.length/2);
    var pivot = arr[pivotIndex];
    var left = [];
    var right = [];
    for(var i=0;i<arr.length;i++){
        if(arr[i]<pivot){
            left.push(arr[i]);
        }else if(arr[i]>pivot){
            right.push(arr[i]);
        }
    }
    return quickSort(left).concat(pivot).concat(quickSort(right));
}
console.log("快速排序:"+quickSort(arr));

参考:http://www.cnblogs.com/dushao/p/6004883.html

posted @ 2017-04-06 17:26  Shuqi_memo  阅读(184)  评论(0编辑  收藏  举报