PROGRAMMING IN C LANGUAGE ONLY Write a program that uses a f
PROGRAMMING IN C LANGUAGE ONLY
Write a program that uses a function to search an integer array for a target value. The array values should be: 1, 2 ,5, 7, 8, 10, 11, 15, 19, 20. The user inputs the value of the target. The program outputs the target value and the index. Use a binary search.
Solution
#include <stdio.h>
int binarySearch(int arr[],int low,int high,int target)
{
if(low>high)
return -1;
int mid = (low+high)/2;
if(arr[mid]==target)
return mid;
else if(arr[mid]>target)
return binarySearch(arr,0,mid-1,target);
else
return binarySearch(arr,mid+1,high,target);
}
int main(void) {
// your code goes here
int arr[] = {1, 2 ,5, 7, 8, 10, 11, 15, 19, 20};
int target;
printf(\"Please input the target you want to search in the array : \");
scanf(\"%d\",&target);
int index = binarySearch(arr,0,9,target);
if(index==-1)
printf(\"Target not found.\");
else
printf(\"Target found at %d\",index);
return 0;
}
OUTPUT:
Please input the target you want to search in the array : 20
Target found at 9
