The binary search works with already sorted array elements. Let us say x is to be search on sorted array then first we will compare x element with middle of the array if it success eds then say element found else check if the element is greater or lesser than the x element and follow the same process repeatedly until desired result is found or say not found.

Here is a C program for binary search :

Here is a C program for binary search :

`#include<stdio.h> #include<conio.h> int count=0; int bin(int item,int a[],int low,int hi) { int mid; if(low>hi) return -1; mid=(low+hi)/2; return (item = = a[mid] ? mid: item<a[mid] ? bin(item,a,low,mid-1): bin(item,a,mid+1,hi)); } int main() { int n,i,a[20],item,pos; printf("enter the size of the array \n"); scanf("%d",&n); printf("enter the array element \n"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("enter the element to be searched \n"); scanf("%d",&item); pos=bin(item,a,0,n-1); if(pos==-1) { printf("element is not found \n"); } else { printf("element is present \n"); } printf("the number of execution is %d\n",count); getch(); }`

รจ 0(nlogn)

good,, !

ReplyDelete