fork download
  1. // Marvyn Jesse De La Torre CS1A Chapter 8 #3 pg.487
  2. //
  3. /*************************************************************
  4. *
  5. * Binary Search Lottery
  6. *
  7. * This program uses binary search to find a number in
  8. * a sorted array of lottery numbers.
  9. *
  10. * Input:
  11. * win: The number entered by the user
  12. *
  13. * Output:
  14. * Displays whether the number was found.
  15. *************************************************************/
  16.  
  17. #include <iostream>
  18. using namespace std;
  19.  
  20. int binary(int arr[], int size, int win);
  21.  
  22. int main()
  23. {
  24. int arr[] = {
  25. 13579, 26791, 26792, 33445, 55555,
  26. 62483, 77777, 79422, 85647, 93121
  27. };
  28.  
  29. int size = sizeof(arr) / sizeof(arr[0]);
  30. int win;
  31.  
  32. cout << "Enter the number to search for: ";
  33. cin >> win;
  34.  
  35. int position = binary(arr, size, win);
  36.  
  37. if (position == -1)
  38. {
  39. cout << "Number not found." << endl;
  40. }
  41. else
  42. {
  43. cout << "Number found." << endl;
  44. }
  45.  
  46. return 0;
  47. }
  48.  
  49. int binary(int arr[], int size, int win)
  50. {
  51. int first = 0;
  52. int last = size - 1;
  53. int position = -1;
  54.  
  55. while (position == -1 && first <= last)
  56. {
  57. int middle = (first + last) / 2;
  58.  
  59. if (arr[middle] == win)
  60. {
  61. position = middle;
  62. }
  63. else if (arr[middle] > win)
  64. {
  65. last = middle - 1;
  66. }
  67. else
  68. {
  69. first = middle + 1;
  70. }
  71. }
  72.  
  73. return position;
  74. }
Success #stdin #stdout 0s 5352KB
stdin
62483
stdout
Enter the number to search for: Number found.