Thursday 26 April 2018

Program to Perform Binary Search Recursively using C Language

Program :-


#include<stdio.h>
int A[100];
int binsrch(int item,int low,int high)  //Entering the function to perform Binary search
{
int mid;  //Assigning values
mid=(low+high)/2;
if(low>high)  //Return -1 if low>high else return 'mid' value
return -1;
else if(A[mid]==item)
return mid;
if(A[mid]>item)  //Recurssion starts
binsrch(item,low,mid-1);
if(A[mid]<item)
binsrch(item,mid+1,high);
}
void main()  //Entering 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,0,n-1);  //Call the function to perform binary search
if(pos==-1)  //Printing if not found else 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

How to Invert an SVG image using CSS ?

You can invert your svg easily by using following css code svg { -webkit-filter: invert(100%); /* safari 6.0 - 9.0 */ filter...