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?
- A. About n log n moves, about 1.7 x 10^6
- B. About n^2 / 2 element moves, about 5 x 10^9 for n = 10^5
- C. About n moves in total, since each memmove is constant
- 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
- A program uses a 2D table of size 1000 x 1000 with an O(1) update per cell and 1000 passes. How many cell updates are done?
- The number of comparisons a merge of two sorted arrays of sizes 4 and 6 makes in the worst case is at most?
- struct P { int a[3]; }; struct P p = {{1, 2, 3}}; struct P q = &p; printf("%d", (q->a + 2)); What is printed?
- char words[] = {"ab", "cd", "ef"}; char pp = words + 1; printf("%s", pp + 1); What is printed?
- int a[] = {10, 20, 30}; int p = a; p++; printf("%d", p + p[1]); What is printed?
- int x = 1, y = 2; int p = &x, pp = &p; pp = &y; printf("%d %d", x, p); What is printed?