Implement Binary Search Algorithm

The assignment I'm working on is creating a recursive binary tree function that runs O(log n) in the worst case.

I tested this and it works, but I don't know if this is the typical way to implement and use a binary search function. Can anyone provide feedback on this?

Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

/**
 *  Description: Recursive function to find position of key
 *  @param sorted array , key , lower bound , upper bound
 *  @return position at which the key exists or -1 if not found
 */
int binarySearch( int arr[] , int x , int low , int high )
{
    if( low <= high ) {
        int mid = ( high + low ) / 2;

        if( arr[mid] == x ) {
            return mid;
        }
        else if( arr[mid] > x ) {
            binarySearch( arr , x , low , mid - 1 );
        }
        else {
            binarySearch( arr , x , mid + 1 , high );
        }
    }
    else {
        return -1;
    }
}

int main()
{
    int arr[5] = { 1 , 2 , 3 , 4 , 5 };

    std::cout << "Position of 3 is " << binarySearch( arr , 3 , 0 , 4 );
}
Last edited on
Topic archived. No new replies allowed.