Difference between returning a function and calling a function in recursion

Viewed 48

Here is a simple code of Binary Search in C++:

int binarySearch(vector<int> &vec, int start, int end, int element) {
    int middle = 0;
    if (start <= end) {
        middle = start + (end - start) / 2;
        if (vec[middle] == element) {
            return middle;
        }
        else if (vec[middle] < element) {
            binarySearch(vec, middle + 1, end, element);
        }
        else {
            binarySearch(vec, start, middle - 1, element);
        }
    }
    return -1;
}

It always produces the result -1. Now, I know that in a function's stack unwinding phase, the last return -1 gets called.

However, the following code works just fine:

int binarySearch(vector<int> &vec, int start, int end, int element) {
    int middle = 0;
    if (start <= end) {
        middle = start + (end - start) / 2;
        if (vec[middle] == element) {
            return middle;
        }
        else if (vec[middle] < element) {
            return binarySearch(vec, middle + 1, end, element);
        }
        else {
            return binarySearch(vec, start, middle - 1, element);
        }
    }
    return -1;
}

I want to know what exactly is the difference between returning a function and calling a function?

0 Answers
Related