代码改变世界

js查找

2019-04-23 19:45  huoit  阅读(478)  评论(0)    收藏  举报

 

 

 

//对象克隆
function main_clone(fromObject, toObject) {
    var copy = toObject || {};
    for (var i in fromObject) {
        if (fromObject[i] == null)
        { copy[i] = fromObject[i]; }
        else
        {
            if (typeof fromObject[i] === 'object') {
                copy[i] = (fromObject[i].constructor === Array) ? [] : {};
                main_clone(fromObject[i], copy[i]);
            } else {
                copy[i] = fromObject[i];
            }
        };
    }
    return copy;
};
/** 
 * [binarySearch 二分查找] 
 * @param  {[type]} value      [查找元素] 
 * @param  {[type]} arr        [数组] 
 * @param  {[type]} startIndex [开始索引] 
 * @param  {[type]} endIndex   [结束索引] 
 * @return {[type]}            [返回查找元素的索引] 
 */
function main_binarySearch(value, arr, startIndex, endIndex) {
    if (!value || !(arr instanceof Array)) return;
    var len = arr.length,
        startIndex = typeof startIndex === "number" ? startIndex : 0,
        endIndex = typeof endIndex === "number" ? endIndex : len - 1,
        midIndex = Math.floor((startIndex + endIndex) / 2),
        midval = arr[midIndex];
    if (startIndex > endIndex) return;
    if (midval == value) {
        return midIndex;
    } else if (midval > value) {
        return main_binarySearch(value, arr, startIndex, midIndex - 1);
    } else {
        return main_binarySearch(value, arr, midIndex + 1, endIndex);
    }
};