Data Structures and Algorithms

A linear search compares the elements of an array of 100 distinct values one by one from the front to find a target. If the target is always in the array and is equally likely to be at any position, what is the average number of comparisons?

  1. AAbout 7
  2. B50.5
  3. C100
Show answer and explanation

Answer: B. 50.5

If the target is at position k, the search makes k comparisons, so the average is (1 + 2 + … + 100) / 100 = 50.5, or (n + 1)/2 in general. The best case (target at the front) takes 1 comparison and the worst case (target at the end) takes 100; both the average and the worst case are proportional to n, so the complexity is O(n). About 7 corresponds to log₂ 100 ≈ 6.6, the number of steps of a binary search, which cannot be used unless the data is sorted.

  • A. This is close to the maximum for a binary search, not the average for a linear search.
  • B. Correct. (1 + 2 + … + 100)/100 = 50.5, or (n + 1)/2 in general.
  • C. This is the worst case, when the target is at the end.
Practice this topic Back to topic

Related calculators

Books on Data Structures and Algorithms Ad

As an Amazon Associate I earn from qualifying purchases.

More Data Structures and Algorithms questions

  1. Compared with an array, which is a correct description of a linked list (a list in which each element holds a pointer to the next element)?
  2. On an empty stack, the operations push 1, push 2, pop, push 3, push 4, pop, pop are performed in this order. In what order are the values removed by pop?
  3. Elements A, B and C are added to an empty queue in this order. Then one element is removed, D is added and one is removed, and E is added and one is removed. In what order are the elements removed?
  4. The expression “3 4 + 2 * 5 −” in reverse Polish notation (postfix notation) is evaluated by pushing each number onto a stack and, for each operator, popping two values, computing the result and pushing it back. What is the result? The left operand of an operator is the value that was pushed earlier.
  5. Which is the correct description of a collision in a hash table?