js 상용 알고리즘

1879 단어
var arr = [1, 2];

var _arr = [].slice.call(arr, 0);

//  bind 
Function.prototype.bind = function(ctx) {
    var _this = this;
    var arg = [].slice.call(arguments, 1);
    var fBind = function() {
        return _this.apply(ctx, arg.concat([].slice.call(arguments)))
    }

    return fBind;
}

//  
var quickSort = function(arr) {
    if (arr.length <= 1) return arr;
    var pivotIndex = Math.floor(arr.length / 2);    
    var pivot = arr.splice(pivotIndex, 1)[0];
    var left = [];
    var 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));

}

//  
var bubbleSort = function(arr) {
    for(var i = 0; i < arr.length; i++) {
        for(var j = i + 1; j < arr.length; j++) {
            if(arr[i] > arr[j]) {
                var temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }

    return arr;
}

//  
var distinct = function(arr) {
    var obj = {}, result = [];
    for(var i = 0; i < arr.length; i++) {
        if(!obj[arr[i]]) {
            obj[arr[i]] = 1;
            result.push(arr[i]);
        }
    }
    return result;
}

//  
var distinct1 = function(arr) {
    var result = [];
    for(var i = 0; i < arr.length; i++) {
        for(var j = i + 1; j < arr.length; j++) {
            if(arr[i] === arr[j]) {
                j = ++i
            }
        }
        result.push(arr[i]);    
    }
    return result;
}

// indexOf 
var distinct2 = function(arr) {
    var result = [];
    arr.forEach(function(v, i) {
        var bool = arr.indexOf(v, i + 1);
        if(bool === -1) {
            result.push(v);
        }
    })
    return result;
}



좋은 웹페이지 즐겨찾기