开发者

Returning Value in C

I have a problem with the return value in a binary search that I wrote.

I have the following:

int binarySearch(char *instructions[], int low, int high, char *string);

int main() {
    char *instructions[];  // some array of strings - it does not include the string "jk"
    char *string = "jk";
    int high = inst_len;
    int x = binarySearch(instructions, 0, high, string);
    if (x == -1)
        printf("not found");
    else if (x == -2)
    printf("error");
    else
    printf("Found at %d", x);
}

int binarySearch(char *instructions[], int low, int high, char *string) {

    int mid = low + (high - low) / 2;

    // Not found
    if (high <= low)
        return -1;

    // If instructions[mid] is less than string
    else if (strcmp(instructions[mid], string) > 0)
        binarySearch(instructions, low, mid-1, string);

    // If instructions[mid] is larger than string
    else if (strcmp(instructions[mid], string) < 0)
        binarySearch(instructions, mid+1, high, string);

    // Return position
    else
        return mid;
}

No matter what, in main, binarySearch is always returning 0. However, when I put print statements in the binary search algo开发者_C百科rithm, I get -1 being returned. Why is this happening?? This is very weird!


You want this:

// If instructions[mid] is less than string
else if (strcmp(instructions[mid], string) > 0)
    return binarySearch(instructions, low, mid-1, string);

// If instructions[mid] is larger than string
else if (strcmp(instructions[mid], string) < 0)
    return binarySearch(instructions, mid+1, high, string);

Note the "return" part.

You're also doing the compare more times than you have to; you can store the result of strcmp so that you only do it once:

int r = strcmp(instructions[mid], string);

if (r > 0)
    return binarySearch(instructions, low, mid-1, string);
else if (r < 0)
    return binarySearch(instructions, mid+1, high, string);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜