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 ?
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).
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:
linear such that all prior elements in linear are strictly smaller than key and it is equal to key, the function will return its indexkey the function will return -1.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With