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

Discussion

A binary search on a sorted array of n elements takes

  • A.O(n)
  • B.O(log n)
  • C.O(1)
  • D.\(O(n^{2})\)

Answer: B

Binary search takes O(log n) time.

Each comparison with the middle element halves the part of the array that can still hold the target. Starting from n elements, after k comparisons at most n/2k remain, so the search ends after about log2 n steps: around 20 comparisons for a million elements.

O(n) is linear search, which checks elements one by one. O(1) is direct indexing or an average hash-table lookup, and O(n2) is the cost of simple sorts such as bubble sort, not of searching a sorted array.

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

Post your comment

Please log in or register to post a comment.