Skip to content
Official PYQ · 2002

GATE CS 2002 Q2.10 — Searching, Sorting, Hashing

Explain with AI

Consider the following algorithm for searching for a given number xx in an unsorted array A[1..n]A[1..n] having nn distinct values:

  1. Choose an ii at random from 1..n1..n
  2. If A[i]=xA[i] = x, then Stop else Goto 1;

Assuming that xx is present in AA, what is the expected number of comparisons made by the algorithm before it terminates?

Choose one option
View worked solution

Answer: A

The algorithm describes a randomized search with replacement. Let's analyze the probability of finding the element xx in each step:

  • Since the array A[1..n]A[1..n] has nn distinct elements and xx is guaranteed to be present, there is exactly one index ii such that A[i]=xA[i] = x.
  • In each step, an index ii is chosen uniformly at random from the set of indices.
  • The probability of success (finding xx) in any single trial is:
    p=1np = \frac{1}{n}
  • The probability of failure in any single trial is:
    q=1−p=1−1nq = 1 - p = 1 - \frac{1}{n}

Since the choices in each step are independent, the number of trials NN required to find xx follows a Geometric distribution with success probability p=1np = \frac{1}{n}.

The expected number of trials (which is equal to the expected number of comparisons, as each trial makes exactly one comparison) is given by the expectation of a geometric random variable:

E[N]=1p=11/n=nE[N] = \frac{1}{p} = \frac{1}{1/n} = n

Thus, the expected number of comparisons made by the algorithm before it terminates is nn.

Correct Option: A

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Searching, Sorting, Hashing questions