Binary Search

二分搜索

Search

  • The most common operation in Computer Science
    搜索也是计算机科学的基础操作
  • Search in a Sorted Array
    搜索通常是在一个已排序的数组中
    • How to search? You can always go through the whole Array
      确实只要遍历数组,你一定能文成搜索
    • Is there a way to search easier?
      有没有更好的方法

What is Binary Search

  • Binary search compares the target value to the middle element of the array
    二分法比较的是target和中值的大小
  • If they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful or the remaining half is empty.
    如果不等,则有一半的数组不用再被搜索
  • It is the fastest way to search in a sorted array.
    二分法是最快的在已排序数组中的搜索算法

Example Code

public int BinarySearch(int[] A, int target) {
    int begin = 0;
    int end = A.length;
    while (begin < end) {
        int mid = (end + begin) / 2;
        if (A[mid] == target) {
            return mid;
        } else if (A[mid] < target) {
            begin = mid + 1;
        } else {
            end = mid;
        }
    }
    return -1;
}
def binary_search(A, target):
    begin = 0
    end = len(A)
    while begin < end:
        mid = (begin + end) // 2
        if A[mid] == target:
            return mid
        elif A[mid] < target:
            begin = mid + 1
        else:
            end = mid
    return -1

Example Code - 2

public int BinarySearch(int[] A, int target) {
    int begin = 0;
    int end = A.length - 1;
    while (begin <= end) {
        int mid = (end + begin) / 2;
        if (A[mid] == target) {
            return mid;
        } else if (A[mid] < target) {
            begin = mid + 1;
        } else {
            end = mid - 1;
        }
    }
    return -1;
}
def binary_search(A, target):
    begin = 0
    end = len(A) - 1
    while begin <= end:
        mid = (end + begin) // 2
        if A[mid] == target:
            return mid
        elif A[mid] < target:
            begin = mid + 1
        else:
            end = mid - 1
    return -1

Time Complexity

T(n) = T(\frac{n}{2}) + k
T(n) = O(lgn)

Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

给定排序数组和目标值,如果找到目标,则返回索引。 如果没有,请返回索引按顺序插入的索引。

您可以假设数组中没有重复项。

Examples:

[1,3,5,6], 5 → 2 ; [1,3,5,6], 2 → 1 ; [1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

public int searchInsert(int[] A, int target) {
    int begin = 0;
    int end = A.length - 1;
    int mid = 0;
    while (begin < end) {
        mid = (begin + end) / 2;
        if (A[mid] == target) {
            return mid;
        } else if (A[mid] > target) {
            end = mid;
        } else if (A[mid] < target) {
            begin = mid + 1;
        }
    }
    return begin;
}

要注意while循环中begin和end的设置

这是找符合条件的中的上限

def searchInsert(A, target):
    begin = 0
    end = len(A) - 1
    while begin <= end:
        mid = (begin + end) // 2
        if A[mid] == target:
            return mid
        elif A[mid] > target:
            end = mid - 1
        else:
            begin = mid + 1
    return begin

Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

 

实现int sqrt(int x)。

计算并返回x的平方根。

Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

public int mySqrt(int x) {
    if (x <= 1) {
        return x;
    }
    long begin = (long)0;
    long end = (long)x / 2 + 1;
    while (begin < end) {
        long p = (end + begin + 1) / 2;
        if (p * p == x) {
            return (int)p;
        } else if (p * p < x) {
            begin = p;
        } else {
            end = p - 1;
        }
    }
    return (int)begin;
}

这是在符合要求的里面找下限

def mySqrt(x):
    if x <= 1:
        return x
    begin = 0
    end = x // 2 + 1
    while begin < end:
        p = (end + begin + 1) // 2
        if p * p == x:
            return p
        elif p * p < x:
            begin = p
        else:
            end = p - 1
    return begin

Binary Search Summary

  • The fastest way to search in sorted array. O(logN)
  • Be careful with INFINITE LOOP.
    当心循环走不完
    • int mid = (begin + end) / 2; begin = mid + 1;
    • int mid = (begin + end + 1) / 2; end = mid - 1;
    • Condition to terminate the loop 什么时候停
    • Condition for edge cases 边界条件
    • In each loop iteration, there can be only two cases.
      在循环中,只有两种情况
      • The range of [begin, end] decrease. 范围变小
      • Jump out of the loop 跳出循环
  • Make sure all cases are taken care of before writing code. 确保考虑了所有情况

Copy of Copy of 12 Binary Search

By ZhiTongGuiGu

Copy of Copy of 12 Binary Search

  • 47