Program :-
#include<stdio.h>
int A[100];
int binsrch(int item,int n) //Entering Binary search funtion
{
void main()//Enter the main function
{
int i,n,item,pos;
printf("Enter the array size "); //Reading the array size
scanf("%d",&n);
printf("Enter the array elements "); //Reading the array elements
for(i=0;i<n;++i)
scanf("%d",&item);
pos=binsrch(item,n); //Calling funtion to perform Binary search
if(pos==-1) // Printing 'not found' or 'position'
Output :-
Eg 1:-
Enter the array size : 5
Enter the array elements : 32 45 18 25 56
Enter the item to be searched : 23
Item not found
Eg 2:-
Enter the array size : 5
Enter the array elements : 32 45 18 25 56
Enter the item to be searched : 18
#include<stdio.h>
int A[100];
int binsrch(int item,int n) //Entering Binary search funtion
{
int low=0; // Assigning values
int high=n-1;
int mid;
mid=(low+high)/2;
while(A[mid]!=item && low<=high) //Searching starts
{
mid=(low+high)/2;}
if(A[mid]==item)
return mid; //Return 'mid' value if found firstif(A[mid]>item) //Comparing starts
high=mid-1;else if(A[mid]<item)
low=mid+1;
return mid; //Return new 'mid' value if found laterif(low>=high) //Return -1 if not found}
return -1;
void main()//Enter the main function
{
int i,n,item,pos;
printf("Enter the array size "); //Reading the array size
scanf("%d",&n);
printf("Enter the array elements "); //Reading the array elements
for(i=0;i<n;++i)
scanf("%d",&A[i]);printf("enter the item to be searched "); //Reading the item to be searched
scanf("%d",&item);
pos=binsrch(item,n); //Calling funtion to perform Binary search
if(pos==-1) // Printing 'not found' or 'position'
printf("Item not found\n");else
printf("The item%d is found at pos %d\n",item,pos+1);}
Output :-
Eg 1:-
Enter the array size : 5
Enter the array elements : 32 45 18 25 56
Enter the item to be searched : 23
Item not found
Eg 2:-
Enter the array size : 5
Enter the array elements : 32 45 18 25 56
Enter the item to be searched : 18
The item 18 is found at the position 3
No comments:
Post a Comment