Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 965
Athirah Hazira Avatar asked Jan 22 '26 03:01

Athirah Hazira


2 Answers

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).

like image 160
peter.petrov Avatar answered Jan 23 '26 17:01

peter.petrov


I believe this function is meant to take a sorted array and returns the index of a given key if it is found in the array and return -1 if there is no matching element in the array.

EDIT: to avoid confusion - in the example you show linear is not sorted. This means that it will not do what I describe above. If linear is not sorted, then the function will do the following:

  • if there is an element in linear such that all prior elements in linear are strictly smaller than key and it is equal to key, the function will return its index
  • Otherwise if there is an element greater than key the function will return -1.
  • Otherwise the return value is not defined in the code snippet you provide.
like image 33
Ivaylo Strandjev Avatar answered Jan 23 '26 19:01

Ivaylo Strandjev