Write a program for Binary Search Method 2 in C

Binary Search Method 2

In binary search first we need the array in sorted order. Then we use divide and conquer method.
We first find the middle position of the array index number then we compare with it. If we have arranged the array in ascending order then if our searched value is less than mid value then we again start searching in first half of the search or if the search value is greater than the mid value then we search in second half of the array.


Program: 

#include<stdio.h>
#include<conio.h>
int main()
{
int n , i , a[10]={1,2,3,4,5,6,7,8,9,10}, k=1;

int first=0 ,item, last=10, mid=(first+last)/2;

printf("Enter the Element you want to search: ");
scanf("%d",&item);


for(i=0;first<last;i++)
{
if(item>a[mid])
{
first=mid+1;
}
else if(item==a[mid-1])
{
printf("\n\n\n\n\t\t\t\tElement is found at %d",mid);
k=0;
break;
}
else //(item<a[mid])
{
last=mid-1;

}

mid=(first+last)/2;
}

if(k==1)
printf("\n\n\n\n\t\t\t\tElement isn't found");
return 0;
}

Previous
Next Post »