Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

PROGRAM TO SEARCH A GIVEN VALUE IN LIST USING BINARY SEARCHING METHOD

#include<iostream.h> #include<conio.h> #include<graphics.h> int bsear(int [],int ,int); void sort(int [],int); void main() { clrscr(); int ar[20],it ,n,k,i; cout<<"enter no. of elements\t"; cin>>n; cout<<"enter array elenments"; for(i=0;i<n;i++) cin>>ar[i]; sort(ar,n); cout<<"\n array after sorting \n"; for(i=0;i<n;i++) cout<<ar[i]<<"\t"; cout<<"enter the no. to be searched\t"; cin>>it; k=bsear(ar,n,it); cout<<"\n no is at position\t\t"<<k; getch(); } int bsear(int ar[],int n,int it) { int mid,i; int beg=0,last=n-1; while(beg<=last) { mid=(beg+last)/2; if(it==ar[mid]) return mid+1; else if(it<ar[mid]) last=mid-1; else beg=mid+1;}

return -1; } void sort(int ar[],int n) { int tmp,ctr=0; for(int i=0;i<n;i++) {for (int j=0;j<(n-1)-i;j++) { if(ar[j]>ar[j+1]) {tmp=ar[j]; ar[j]=ar[j+1]; ar[j+1]=tmp; } } cout<<"array after iteration-"<<++ctr<<"-is"; for(int k=0;k<n;k++) cout<<ar[k]<<" "; cout<<endl; } }

You might also like