演算法(氣泡排序,快排,歸併排序)

weixin_33866037發表於2018-03-28

氣泡排序

    function mySort(arr) {
        for (var i = 0; i < arr.length - 1; i++) {
            for (var j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    var tmp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = tmp;
                }
            }
        }
return arr;
    }

快速排序

    function sort(arr) {
        if(arr.length<=1){
            return arr;
        }

        var middle = arr[0];
        var left = [];
        var right = [];
        for(var i =1;i<arr.length;i++){
            var value = arr[i];
            if (value<middle){
                left.push(value)
            }else {
                right.push(value)
            }
        }

        return sort(left).concat(middle,sort(right))
    }

歸併排序

    function merge(left, right) {
        var result = [];
        while(left.length > 0 && right.length > 0) {
            if(left[0] < right[0]) {
                result.push(left.shift());
            }
            else {
                result.push(right.shift());
            }
        }
        /* 當左右陣列長度不等.將比較完後剩下的陣列項鍊接起來即可 */
        return result.concat(left).concat(right);
    }
    function mergeSort(arr){
        if(arr.length==1) {return arr};
        var mid=Math.floor(arr.length/2);
        var left_arr=arr.slice(0,mid),right_arr=arr.slice(mid);
        return merge(mergeSort(left_arr),mergeSort(right_arr));
    }

相關文章