0

I have the following pseudocode which a sequential search pseudocode and I am trying to understand what return -1 mean. why would we return -1 could someone please explain.

A[n] <-- K
i <-- 0
while A[i] != K do
     i = i + 1
if(i<n)
     return i;
else
     return -1;       //What is this mean ?
matrixCode
  • 111
  • 1
  • 2
  • 7
  • This code is curiously structured. Usually it's bent that way to avoid multiple `return` statements, but there are two. – Quentin Feb 16 '15 at 15:28
  • for this code, it means there's no element equal to K in the array A before the nth index. n is probably the size of the array, so this reduces to: it means array A does not contain any element equal to K. – thang Feb 16 '15 at 15:30

2 Answers2

5

Returning -1 is a way of conveying the fact that the code reached the end without returning in the middle. Returning -1 in this case means that the element K does not exist in the array.

Note that returning 0 is not used for this purpose as it could mean the element is present at the 0th index. If your function was something which could return -1 at some point in the middle, some other return value to indicate failure would have been chosen.

therainmaker
  • 4,253
  • 1
  • 22
  • 41
0

If you were to search a sequence for an element, and return the index of that element, you'd want some way to show that the element wasn't found. A negative value is an invalid index in many languages, so returning -1 could only mean the element couldn't be found for one reason or another.

int index_of(const int *array, int sz, int elem) {
    for (int i = 0; i < sz; ++i) {
        if (array[i] == elem) { // found the element
            return i; // return the index of the element
        }
    }
    return -1; // couldn't find it
}

Then in the calling code you might have

int calling() {
    int array[N];
    // populate array with data ...
    int idx = index_of(array, N, 4); // find where 4 is in the array
    if (idx < 0) {
        // 4 isn't in the array
    } else {
        // 4 IS in the array !
    }
}
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174