fork download
  1.  
  2. //Dione Torrevillas CS1A Chapter 8, P. 487, #4
  3.  
  4. /**********************************************************
  5.  * Class: CS1A
  6.  * Chapter 8 Homework - Programming Challenge #4
  7.  * Title: Charge Account Validation Modification
  8.  *
  9.  * Description:
  10.  * This program uses selection sort to arrange charge account
  11.  * numbers, then binary search to check whether one is valid.
  12.  *
  13.  * INPUT:
  14.  * A charge account number entered by the user.
  15.  *
  16.  * OUTPUT:
  17.  * A message saying whether the number is valid.
  18.  **********************************************************/
  19.  
  20. #include <iostream>
  21. using namespace std;
  22.  
  23. // Put the integer array in ascending order using selection sort.
  24. void selectionSort(int values[], int size)
  25. {
  26. for (int start = 0; start < size - 1; start++)
  27. {
  28. int minIndex = start;
  29.  
  30. // Find the smallest value in the unsorted part.
  31. for (int i = start + 1; i < size; i++)
  32. {
  33. if (values[i] < values[minIndex])
  34. minIndex = i;
  35. }
  36.  
  37. // Put that value at the start of the unsorted part.
  38. int temp = values[start];
  39. values[start] = values[minIndex];
  40. values[minIndex] = temp;
  41. }
  42. }
  43.  
  44. // Return true when target is in the sorted array.
  45. bool binarySearch(const int values[], int size, int target)
  46. {
  47. int first = 0;
  48. int last = size - 1;
  49.  
  50. while (first <= last)
  51. {
  52. int middle = (first + last) / 2;
  53.  
  54. if (values[middle] == target)
  55. return true;
  56. else if (values[middle] > target)
  57. last = middle - 1;
  58. else
  59. first = middle + 1;
  60. }
  61.  
  62. return false;
  63. }
  64.  
  65. int main()
  66. {
  67. const int SIZE = 18;
  68. int accounts[SIZE] = {
  69. 5658845, 4520125, 7895122, 8777541, 8451277, 1302850,
  70. 8080152, 4562555, 5552012, 5050552, 7825877, 1250255,
  71. 1005231, 6545231, 3852085, 7576651, 7881200, 4581002
  72. };
  73.  
  74. int accountNumber; //INPUT - Charge account number from user
  75.  
  76. // The array must be sorted before binary search can work.
  77. selectionSort(accounts, SIZE);
  78.  
  79. cout << "Enter a charge account number: ";
  80. cin >> accountNumber;
  81.  
  82. //OUTPUT - Display whether the account number is valid.
  83. if (binarySearch(accounts, SIZE, accountNumber))
  84. cout << "The charge account number is valid." << endl;
  85. else
  86. cout << "The charge account number is invalid." << endl;
  87.  
  88. return 0;
  89. }
  90.  
Success #stdin #stdout 0.01s 5356KB
stdin
8777541
stdout
Enter a charge account number: The charge account number is valid.