Search code examples
javareturnreturn-valuelinear-search

Function of return -1


Basically what does this return -1 do ?

for an example :

int linear[] = {4, 21, 36, 14, 66, 91, 8, 22, 7, 81, 77, 10};
int key = 77;
for (int i = 0; i < linear.length; i++){
  if (linear[i] > key)
    return -1; //here
  else if (linear[i] == key)
    return i;
}
  • i understand return 1 and return 0 well . but return -1 ?

  • what if the question sounds like this :

Show the way of solving the linear search based on the code given ?


Solution

  • In this case it says/indicates that linear[i] is smaller than your key.

    In some occasions it might also indicate that a key is not found.

    This is a widely used convention (I mean returning -1 in such cases).