arraysalgorithmsearchlinear-search

Question about array in a sequential search


I was wondering if anyone can help explain this to me. From what I know, if I was searching for "red", the answer would be 4. I know it should start from 0, but the online test I took said I was wrong. And said it 3.

But how many time would it search for gold, if gold is not in the array?

How many compares are used for an unsuccessful search for "gold" with sequential search? If an array of strings contains ["black", "blue", "green", "red", "silver", "yellow", "white"].


Solution

  • The index of "red" is 3 in 0-indexed systems and 4 in 1-indexed systems. But the question was not "what is the index of red". The question was "how many comparisons you have to make to find red". And the answer to that question is 4 in all systems.

    The second question was "how many comparisons you have to make to figure out that the thing you are looking for is not in the array". And the answer to that is the array's length, which is 7. Incidentally, same number of comparisons is required to find the last item in the array, which is "white" in this case.