Implement a function that uses binary search to find the index position of a giv
ID: 3762177 • Letter: I
Question
Implement a function that uses binary search to find the index position of a given value kin an array of integers whose eements are in strictly increasing order. searches for a given value k in an array of integers. If the value is found, the function returns the index of the value in the array; otherwise it returns -1. For example, for v = (-2, 4, 5, 6, 8) and k = 1, the function returns -1. and for k = 4 it returns 1. A declaration of the function is given above. Include test code with assertions using <cassert>.
Explanation / Answer
#include <stdio.h>
#include <assert.h>
int binarysearch(int *arr,int low,int high,int k)
{
int middle;
while(low<=high)
{
middle = (low+high)/2;
if(arr[middle]==k)
return middle;
else if(arr[middle]>k)
high = middle-1;
else
low = middle+1;
}
return -1;
}
int main()
{
int arr[5] = {-2, 4, 5, 6, 8};
int result = 0;
result = binarysearch(arr,0,4,4);
printf("Index : %d ",result);
assert(result==1);
result = binarysearch(arr,0,4,1);
printf("Index : %d ",result);
assert(result==-1);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.