Q:

C Program For Binary Search

belongs to collection: Searching C Programs

0

Logic:-

 Binary search logic is simple and very useful. Let's take an example of an array and try to perform a Binary search operation on it. First, we have to know that Binary search applies is only sorted data, so if data is not sorted then you can not apply Binary search.

Now come to point so basically we divide the array data in two parts and compare the elements first iteration, and compare the element of the mid element of an array if the element is less than the array element then again divide the array from staring to midpoint into 2 part and again matches the element if again array element is greater than the element than again divide the array into two parts. If the array element is less the element than again divide the array into two parts starting to mid to end and repeat the step until to the last divide the array. 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include<stdio.h>

main()
{
 //C program for binary search

 int *a,i,itm,s,j,flag=0,low,up,mid,temp;
 
 printf("==================================");
 printf("\nC  Program For Binary Search\n");
 printf("==================================\n");
 
 printf("\nEnter The Size Of An Array :");
 scanf("%d",&s);
 
 a=(int*)malloc(s*sizeof(int));
 
 printf("\nEnter An Elements Of An Array\n");
 for(i=0;i<s;i++)
 {
 scanf("%d",&a[i]);
 }
 
 for(i=1;i<s;++i)
 {
 for(j=0;j<(s-1);++j)
 {
 if(a[j]>a[j+1])
 {
 temp = a[j];
 a[j] = a[j+1];
 a[j+1] = temp;
 }
 }
 }
 printf("\nEnter The Number You Want To Search In An Array :");
 scanf("%d",&itm);
 
 low=0;
 up=s-1;
 mid=(low+up)/2;

 
 if(itm<=a[mid])
 {
 for(i=0;i<=mid;i++)
 {
 if(a[i]==itm)
 flag=1;
 }
 }
 
 if(itm>a[mid])
 {
 for(i=mid;i<s;i++)
 {
 if(a[i]==itm)
 flag=1;
 }
 }
 
 if(flag==1)
 {
 printf("\nNumber Found In an Array \n");
 }
 else 
 {
 printf("\nNumber Not Found In an Array \n");
 }
}

 

Output:

==================================

C Program For Binary Search

==================================

Enter The Size Of An Array :7

Enter An Elements Of An Array

15

115

175

250

365

808

999

Enter The Number You Want To Search In An Array :808

Number Found In an Array 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< C Program For Linear Search...