Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the time complexity of the binary search algorithm ?

  • A.O(1)
  • B.O(log n)
  • C.O(n)
  • D.O(n log n)

Answer: B

Binary search takes O(log n) time.

On a sorted array, each comparison with the middle element discards half of the remaining range. After k comparisons n/2k elements remain, so at most about log2 n comparisons are needed. A million elements need only about 20.

O(1) would mean finding the item in one step whatever the size, which only hashing approaches. O(n) is linear search, and O(n log n) is the cost of sorting the array first.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.