Data Structures & AlgorithmsEasyInfosys · Capgemini pattern

A sorted array holds n elements and has spare capacity. What is the worst-case time to insert a new element so that the array stays sorted?

  1. A. O(log n)
  2. B. O(1)
  3. C. O(n log n)
  4. D. O(n)

Correct answer: D. O(n)

Binary search finds the position in O(log n), but every element after that position must shift one place right, which is O(n) when inserting at the front. Re-sorting (O(n log n)) is never necessary.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic