fork download
  1. //Xinnuo Wanng CS1A Chapter 8 #3 Page.487
  2. /*******************************************************************************
  3.  * Convert Linear to Binary Search
  4.  * _____________________________________________________________________________
  5.  * The program modifies the linear search to binary search.
  6.  * _____________________________________________________________________________
  7.  * Input
  8.  * win : The accepted winning number
  9.  *
  10.  * ****************************************************************************/
  11.  
  12. #include <iostream>
  13. using namespace std;
  14. int binary(int arr[], int size, int win);
  15.  
  16. int main()
  17. {
  18. int arr[]={13579, 26791, 26792, 33445, 55555, 62483, 77777, 79422, 85647,
  19. 93121};
  20. int size = sizeof(arr)/sizeof (arr[0]);
  21. cout << "Enter the winning number: " ;
  22. int win;
  23. cin >> win;
  24. cout << win<< endl;
  25. int m =binary(arr,size,win);
  26. if(m==-1)
  27. {
  28. cout << "None of them win" << endl;
  29. }
  30. return 0;
  31. }
  32.  
  33. int binary(int arr[], int size, int win)
  34. {
  35. bool found = false;
  36. int position = -1;
  37. int first = 0;
  38. int last = size-1;
  39. while (!found && first <= last)
  40. {
  41. int middle = (first + last)/2;//
  42. if(arr[middle] == win)
  43. {
  44. found = true;
  45. position = middle;
  46. cout << "Congradulation!" << endl;
  47. }
  48. else if(arr[middle] > win)
  49. {
  50. last = middle -1;
  51. }
  52. else
  53. {
  54. first = middle +1;
  55. }
  56. }
  57. return position;
  58. }
Success #stdin #stdout 0s 5348KB
stdin
22222
stdout
Enter the winning number: 22222
None of them win