Why does the linear search return for element not found have to be -1?

7

Why should I return -1 at the end of a linear search if the element was not found?

int linearSearch(int[] list, int size, int key){
        for(int index=0; index<size; index++)
          if(list[index]==key)
            return index;
        return -1;
      }//linearSearch
    
asked by anonymous 23.11.2017 / 01:54

2 answers

7

You do not have to do this, you can do several things, but you need to inform in some way that you did not find the element you are looking for. One of the most used ways is to return a value that would be impossible in a search that finds the element, and usually a negative is adequate, the -1 is convened to have a certain consistency.

Some people criticize this sort of thing. I am a supporter whenever it makes sense, as seems to be the case .

    
23.11.2017 / 02:02
0

Here you can also opt for other solutions such as throwing an exception when the search fails, or passing a flag by parsing that has a similar effect to the -1 return. However this latter solution is not recommended for various reasons.

Basically, as Maniero said, the important thing is that you have the indication that you did not find and that this information does not present any doubts.

    
12.12.2017 / 15:26