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

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

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

**(A)** n

**(B)** n – 1

**(C)** 2n

**(D)** n/2

**Answer:** **(A)** **Explanation:**

If you remember the coin and dice questions, you can just guess the answer for the above.

Below is proof for the answer.

Let expected number of comparisons be E. Value of E is sum of following expression for all the possible cases.

number_of_comparisons_for_a_case * probability_for_the_case

Case 1

If A[i] is found in the first attempt number of comparisons = 1 probability of the case = 1/n

Case 2

If A[i] is found in the second attempt number of comparisons = 2 probability of the case = (n-1)/n*1/n

Case 3

If A[i] is found in the third attempt number of comparisons = 2 probability of the case = (n-1)/n*(n-1)/n*1/n

There are actually infinite such cases. So, we have following infinite series for E.

E = 1/n + [(n-1)/n]*[1/n]*2 + [(n-1)/n]*[(n-1)/n]*[1/n]*3 + …. (1)

After multiplying equation (1) with (n-1)/n, we get

E (n-1)/n = [(n-1)/n]*[1/n] + [(n-1)/n]*[(n-1)/n]*[1/n]*2 + [(n-1)/n]*[(n-1)/n]*[(n-1)/n]*[1/n]*3 ……….(2)

Subtracting (2) from (1), we get

E/n = 1/n + (n-1)/n*1/n + (n-1)/n*(n-1)/n*1/n + …………

The expression on right side is a GP with infinite elements. Let us apply the sum formula (a/(1-r))

E/n = [1/n]/[1-(n-1)/n] = 1 E = n

## Recommended Posts:

- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 35
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 21
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 20
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 19
- GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 47
- GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 48
- GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 49
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 18
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 17
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 16
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 15
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 14
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 13
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 23
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 24
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 34
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 33
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 32
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 31
- GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 30