Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2015
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. //PROGRAM CODE 9.4
  2. // Function binary search (recursive)
  3. #include<iostream.h>
  4. #include<conio.h>
  5.  
  6. int Binary_Search(int A[],int low,int high,int key)
  7. {
  8. int mid;
  9. if(low<=high) {
  10. mid=(low+high)/2;
  11. if(A[mid] == key)
  12. {
  13. //cout<<"\n\t Found";
  14. return mid;
  15. }
  16. else if(key<A[mid])
  17. return Binary_Search(A,low,mid-1, key);
  18. else
  19. return Binary_Search(A,mid+1,high, key);
  20. }
  21. return -1;
  22. }
  23. void main()
  24. {
  25.  
  26. int i, size,A[20],ans,key;
  27. clrscr();
  28. cout<<"Enter array size = ";
  29. cin>>size;
  30.  
  31. cout<<"\n Enter array elements";
  32. for (i=0;i<size;i++)
  33. {
  34. cin>>A[i];
  35. }
  36. cout<<"Enter the element to be search =";
  37. cin>>key;
  38. ans = Binary_Search(A,0,size,key);
  39. if(ans==-1)
  40. cout<<"\n Not found";
  41. else
  42. cout<<"Found";
  43.  
  44. getch();
  45. }
  46.  
  47. /*********************OUTPUT *******************************
  48. Enter array size = 5
  49.  
  50. Enter array elements
  51. 1 2 3 4 5
  52.  
  53. Enter the element to be search = 5
  54.  
  55. Found
  56.  
  57. Enter array size = 5
  58.  
  59. Enter array elements
  60. 1 2 3 4 5
  61.  
  62. Enter the element to be search = 25
  63.  
  64. Not Found
  65.  
  66. ***********************************************************/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement