Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

14.7 Lab 9: Recursive Search Implement a recursive binary search function. bSear

ID: 3844943 • Letter: 1

Question

14.7 Lab 9: Recursive Search

Implement a recursive binary search function.

bSearch passes in an array of integers, the size of the array, and the value the function is searching for. The function should return the index where found or -1 if not found. You will want to implement a recursive helper function that passes in the array, the value to be located, and the beginning and ending of the range of values to search within.

Use the provided main function to test your search function. Be sure not to use a loop of any kind in any of the functions you write.

#include

Explanation / Answer

#include <stdio.h>


int bsearch(int array[], int l, int r, int ele)
{
if (r >= l)
{
       int middle = l + (r - l)/2;

       if (array[middle] == ele) return middle;

       // in left subarray
       if (array[middle] > ele) return bsearch(array, l, middle-1, ele);

       return bsearch(array, middle+1, r, ele);
}

return -1;
}

int main(void)
{
int array[] = {2, 3, 4, 10, 40};
int n = sizeof(array)/ sizeof(array[0]);
int ele = 10;
int resultindex = bsearch(array, 0, n-1, ele);
(resultindex == -1)? printf("the given element not in the array")
               : printf("the given element present at %d", resultindex);
return 0;
}

output:

:the given element present at 3

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote