Size of array is taken from user.. Elements are entered by user in order (ascending or descending).. user is asked for the element to be searched... Search is performed..
Select To use this code as it is.. select and copy paste this code into code.cpp file :)
- #include<conio.h>
- #include<iostream.h>
- void main()
- {
- clrscr();
- int a[100],i,loc,mid,beg,end,n,flag=0,item;
- cout<<"How many element: ";
- cin>>n;
- cout<<"Enter (IN ORDER) the elements of array: "<<endl;
- //Coding by: Snehil Khanor
- //http://WapCPP.blogspot.com
- for(i=0;i<n;i++)
- cin>>a[i];
- cout<<"Enter the element to be searched: ";
- cin>>item;
- loc=0;
- beg=0;
- end=n-1;
- while((beg<=end)&&(item!=a[mid]))
- {
- mid=(beg+end)/2;
- if(item==a[mid])
- {
- cout<<"Search successful :)";
- loc=mid;
- cout<<"Position of the Item: "<<loc+1;
- flag=flag+1;
- }
- else if(item<a[mid])
- end=mid-1;
- else
- beg=mid+1;
- }
- if(flag==0)
- {
- cout<<"Search NOT sucessfull :( ";
- }
- getch();
- }
2 comments:
It's wrong.. The while loop is while(beg<=end)..
I didn't understand anything from this . Sorry
Post a Comment