ProgrammingVery hard
Which is the correct way to count distinct keys in a sorted struct array a[0..n-1] (n >= 1) by key?
- A. count = 1; for (i = 1; i < n; i++) if (a[i].key != a[i - 1].key) count++;
- B. count = 0; for (i = 0; i < n; i++) if (a[i].key != a[i + 1].key) count++;
- C. count = n; for (i = 1; i < n; i++) if (a[i].key == a[i - 1].key) count--;
- D. count = 1; for (i = 0; i < n; i++) if (a[i].key > a[i + 1].key) count++;
Correct answer: A. count = 1; for (i = 1; i < n; i++) if (a[i].key != a[i - 1].key) count++;
The first record always starts a group, so count begins at 1. Each new key differing from its predecessor adds one. The other versions read past the array or count the wrong thing.
More C Programming questions
- A sorted array of records is searched for the first record whose key is at least x (a lower bound). Which loop is correct?
- An array of 2 x 10^5 records must be answered with 2 x 10^5 queries, each asking how many records have key <= q. Which approach is correct…
- After removing duplicate keys from a sorted array of records with the two-index method (keep a[w] when its key differs from the last kept…
- Bubble sort on the records of 4 keys {4, 3, 2, 1} with a swap count: how many swaps are made?
- A struct array holds records with an int key; the program calls qsort with the comparator (int)(a->key - b->key) for keys near INTMAX and…
- A bsearch call uses a key of type int but the array holds struct records with an int field. What is the correct way to compare?