1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
void sort(int ar[],int i,int j)
{
int s=ar[i],pos,f=0;
for(int k=i;k<j;k++)
{
if(ar[k]<s)
{
s=ar[k];
pos=k;
f=1;
}
if(f)
{
ar[pos]=ar[i];
ar[i]=s;
}
f=0;
}
if(i==j)
return;
else
sort(ar,++i,j);
}
int bin_search(int a[],int l,int u,int k)
{
if(l>u)
{
cout<<"\n SEARCH NOT POSSIBLE"; return -1;
}
if(l==u)
{
if(a[l]==k)
return l+1;
else
cout<<"\n UNSUCESSFULL SEARCH";
return -1;
}
else
{
int m=(l+u)/2;
if(a[m]==k) return m+1;
if(a[m]>k)
bin_search(a,l,m-1,k);
else
bin_search(a,m+1,u,k);
}
}
int main()
{
int ch,a[80],n;
cout<<"\n ENTER NUMBER OF ELEMENTS IN ARRAY: ";
cin>>n;
cout<<"\n ENTER ARRAY ELEMENTS: \n";
for(int i=0;i<n;i++) cin>>a[i];
sort(a,0,n);
cout<<"\n sorted array: ";
for(int i=0;i<n;i++) cout<<a[i]<<" ";
cout<<"\n ENTER ELEMENT TO BE SEARCHED: ";
cin>>ch;
ch=bin_search(a,0,n-1,ch);
if(ch!=-1) cout<<"\n ELEMENT FOUND AT: "<<ch;
return 0;
}
|