varungurnaney

HSC: Binary Search

Feb 7th, 2015
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int a[100],n,i,beg,end,mid,item;
  7.  
  8. cout<<"\n------------ BINARY SEARCH ------------ \n\n";
  9. cout<<"Enter No. of Elements= ";
  10. cin>>n;
  11.  
  12. cout<<"\nEnter Elements in Sorted Order=\n";
  13. for(i=1;i<=n;i++)
  14. {
  15. cin>>a[i];
  16. }
  17.  
  18. cout<<"\nEnter Item you want to Search= ";
  19. cin>>item;
  20.  
  21. beg=1;
  22. end=n;
  23.  
  24. mid=(beg+end)/2;                       // Find Mid Location of Array
  25.  
  26. while(beg<=end && a[mid]!=item)      // Compare Item and Value of Mid
  27. {
  28. if(a[mid]<item)
  29. beg=mid+1;
  30. else
  31. end=mid-1;
  32.  
  33. mid=(beg+end)/2;
  34. }
  35.  
  36. if(a[mid]==item)
  37. {
  38. cout<<"\nData is Found at Location : "<<mid;
  39. }
  40. else
  41. {
  42. cout<<"Data is Not Found";
  43. }
  44. getch();
  45. }
Advertisement
Add Comment
Please, Sign In to add comment