C Programming code for Binary Search of an Array – KLE Tech

Write a Modular C Programming Code for Binary Search of a 1D Array?

CODE:

#include<stdio.h>

void readArray(int[],int);
void Binary(int A[],int n,int key);

int main()
{
int n,occ=0,key,flag;
int arr[100];
printf("Enter the size of Array: ");
scanf("%d",&n);
printf("Enter the elements of array: \n");
readArray(arr,n);
printf("Enter the elements to be searched in array: \n");
scanf("%d",&key);

flag=binary(arr,n,key);
if(flag==1)
printf("Serach is successful!!!");
else
printf("Serach not successful!!!");

}

void readArray(int arr[],int n)
{
int i;
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
}

void displayArray(int arr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d ",arr[i]);
}
}

void binary(int arr[],int n,int key)
{
int lower,upper,mid;

lower=0;
upper=n-1;

while(lower<upper)
{
mid=(lower+upper)/2;
if(key==arr[mid])
return(1);
else if(key<arr[mid])
upper=mid-1;
else
lower=mid+1;
}

}

OUTPUT

Enter the size of Array: 5
Enter the elements of array:
3
6
4
9
5
Enter the elements to be searched in array:
9
Serach not successful!!!
Process returned 0 (0x0) execution time : 13.911 s
Press any key to continue.

 

Please find some more codes of 1D Arrays, 2D Arrays, Pointers on the below page:

Top 100+ C Programming codes – KLE Technological University

 

Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

Welcome to FactsPrime

Sorry, We have detected that you have activated Ad-Blocker. Please Consider supporting us by disabling your Ad Blocker, It helps us in maintaining this website. To View the content, Please disable adblocker and refresh the page.

Thank You !!!