logo CodeStepByStep logo


Language/Type: C++ recursion return
Author: Marty Stepp (on 2016/06/16)

Write a recursive function named binarySearch that accepts a reference to a sorted Vector of integers and an integer target value and uses a recursive binary search algorithm to find and return an index at which that target value is found in the vector. If the target value is not found in the vector, return -1. The following code shows some example calls and their expected return values:

        // index  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16
Vector v;
            v += -4,  2,  7, 10, 15, 20, 22, 25, 30, 36, 42, 50, 56, 68, 85, 92, 103;

int index = binarySearch(v, 42);   // 10
int index = binarySearch(v, 66);   // -1

You should assume that the vector's elements are already sorted; you do not need to handle the case of an unsorted vector. Your function must be recursive and must use a binary search algorithm. Do not use loops or auxiliary data structures.

Type your solution here:

This is a function problem. Write a C++ function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.

Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.

© Marty Stepp, all rights reserved.