In: Computer Science
Binary search program:
//declare header file
#include <stdio.h>
//display_array function displays the array eleements
void display_array(int* a,int N){
int i=0;
printf("array eleements are:");
//traversing through array to print eleements
for(i=0;i<N;i++){
printf("%d\t",a[i]);
}
}
//binary_search function returns the search index in the
array
int binary_search(int* a,int N,int k){
//declaration of variables
int first,last,middle;
first = 0;
last = N - 1;
middle = (first+last)/2;
//traversing through array
while (first <= last) {
//checking if the search element is less than mid value
if (a[middle] < k)
first = middle + 1;
//if the search element is found return the index of element
else if (a[middle] == k) {
return middle;
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
return -1;
}
//start of main
int main()
{
//declaration of variables
int c,N,i,k;
//asking the user to enter array size
printf("Enter the number of elements");
scanf("%d",&N);
int a[N];
//asking the user to enter array elements
printf("enter array elements\n");
for(i=0;i<N;i++){
scanf("%d",&a[i]);
}
//prompting the user for search element
printf("\nEnter the element which you want to search:");
scanf("%d",&k);
//function calling
display_array(&a,N);
//storing the return value of binary_search function in c
c=binary_search(&a,N,k);
//printing the search element index
printf("\nkey element found at location:%d",c);
return 0;
}
OUTPUT:
NOTE:
1.There are warnings but the program will run successfully.