How do you calculate the big oh of the binary search algorithm?

后端 未结 2 489
孤街浪徒
孤街浪徒 2020-12-10 08:07

I\'m looking for the mathematical proof, not just the answer.

2条回答
  •  臣服心动
    2020-12-10 08:34

    The recurrence relation of binary search is (in the worst case)

    T(n) = T(n/2) + O(1)
    

    Using Master's theorem

    enter image description here

    • n is the size of the problem.
    • a is the number of subproblems in the recursion.
    • n/b is the size of each subproblem. (Here it is assumed that all subproblems are essentially the same size.)
    • f (n) is the cost of the work done outside the recursive calls, which includes the cost of dividing the problem and the cost of merging the solutions to the subproblems.

    Here a = 1, b = 2 and f(n) = O(1) [Constant]

    We have f(n) = O(1) = O(nlogba)

    => T(n) = O(nlogba log2 n)) = O(log2 n)

提交回复
热议问题