Classic interview questions: binary search/half search

Thought:

适用于有序的顺序表;
给定值key,与表中中间的元素进行比较。如果相等,则查找成功;若不相等,如果key小于中间元素的关键字,则所需查找的元素在顺序表的前半部分,如果是大于,则所需查找的元素在顺序表的后半部分。在缩小的范围内继续同样的查找,一直重复直达找到位置,或者确定表中没有所需要查找的元素,则查找不成功,返回查找失败的信息。
中间元素的位置由 (low+high)/2决定(如果遇到小数,就向下取整/取小);

Average lookup length:

Success: The number of nodes on the path from the root node to the destination node.
    全部节点是非叶子结点的层数**该层结点数)/总共的非叶子结点数
Failed: The number of nodes on the path from the root node to the parent node of the corresponding failed node.
    (有叶子结点的层数**该层的叶子结点数)/叶子结点总数

Advantages and disadvantages:

The search speed is fast, the number of comparisons is small, and the average performance is good;

The table to be looked up is required to be an ordered table, and it is difficult to insert and delete;

Application scenarios:

Therefore, binary search is especially suitable for linear tables that are rarely changed once established, but often need to be looked up.
For those linear tables that are rarely searched and often need to be changed, a linked list can be used as a storage structure for sequential search. Binary search cannot be implemented on linked lists.

// 非递归
function binarySearch(arr, key) {
    var low = 0;
    var high = arr.length - 1;

    while (low <= high) {
        var mid = parseInt((low + high) / 2);
        if (key == arr[mid]) {
            return mid;
        } else if (key > arr[mid]) {
            low = mid++;
        } else {
            high = mid - 1;
        }
    }

}

var arr = [1, 2, 3, 23, 44, 86];
var result = binarySearch(arr, 23);
console.log(result); // 3 返回目标元素的索引值

// 递归
function binary_search(arr,key,low,high) {
    if (low > high){return -1;}

    var mid = parseInt((high + low) / 2); // 3 4 5

    if(arr[mid] == key){
        return mid;
    }else if (arr[mid] > key){
        high = mid - 1;
        return binary_search(arr,key,low,high);
    }else if (arr[mid] < key){
        low = mid + 1;
        return binary_search(arr,key,low,high);
    }
}
var arr = [1,2,3,4,5];
var result = binary_search(arr,5,0,4);
console.log(result); // 4 返回目标元素的索引值  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325944577&siteId=291194637