ProgrammingHard

Each of 10^5 insertions into a dynamic array takes an O(n) memmove to keep the array sorted. Which total cost is right?

  1. A. About n log n moves, about 1.7 x 10^6
  2. B. About n^2 / 2 element moves, about 5 x 10^9 for n = 10^5
  3. C. About n moves in total, since each memmove is constant
  4. D. About n^3 moves, since each insertion shifts a matrix

Correct answer: B. About n^2 / 2 element moves, about 5 x 10^9 for n = 10^5

The i-th insertion moves about i elements, so the sum is quadratic. A balanced tree or a sort at the end is needed.

More C Programming questions

Exams that ask this topic