返回 -1 在伪代码中意味着什么

what does returning -1 mean in a pseudocode

我有以下伪代码,它是一个顺序搜索伪代码,我试图理解 return -1 的含义。为什么我们 return -1 有人可以解释一下。

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 ?

返回 -1 是一种表达代码到达末尾而中间没有 returning 的方式。在这种情况下返回 -1 意味着数组中不存在元素 K。

请注意,returning 0 不用于此目的,因为它可能意味着该元素出现在第 0 个索引处。如果您的函数在中间的某个时间点可以 return -1,则将选择其他一些 return 值来指示失败。

如果您要在序列中搜索某个元素,并且 return 该元素的索引,您需要某种方式来表明未找到该元素。负值在许多语言中是无效索引,因此 returning -1 只能表示由于某种原因无法找到该元素。

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
}

然后在调用代码中你可能有

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 !
    }
}