Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2015
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. //PROGRAM CODE 9.3
  2.  
  3. #include<iostream.h>
  4. #include<conio.h>
  5.  
  6. int Binary_Search_non_recursive(int A[], int n, int key)
  7. {
  8. int low=0,high=n-1,mid;
  9. while(low<=high)
  10. { //iterate while first<=last
  11. mid = (low + high)/2; //calculate
  12. //mid = (first+last)/2)
  13. if(A[mid] == key) //found
  14. return mid; // return position (mid)
  15. else if(key<A[mid])
  16. //not found-look in upper half of list
  17. high=mid-1;
  18. else
  19. low=mid+1; //look in lower half
  20. }
  21. return -1; //return "not found"
  22. }
  23.  
  24. void main()
  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<<"\n\n\t Enter the element to be search = ";
  37. cin>>key;
  38. ans =Binary_Search_non_recursive(A,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