ProgrammingModerate

Which loop is correct and fast enough to find the largest element of an array of 10^7 ints, reading each value once?

  1. A. Sorting the array first and then scanning, about 2 x 10^8 steps
  2. B. Comparing each element with every other element, about 10^14 steps
  3. C. Building a binary tree from every element, about 10^8 nodes
  4. D. A single pass keeping the running maximum, O(n)

Correct answer: D. A single pass keeping the running maximum, O(n)

A single linear pass is the fastest. Sorting is O(n log n), and pairwise comparison is quadratic.

More C Programming questions

Exams that ask this topic