//Sam Trivikraman CS1A Chapter 8, p. 487, #4
//
/*
******************************************************************************
Validate Account Numbers (Modification)
_______________________________________________________________________________
This program validates whether the number inputted is a valid account number.
_______________________________________________________________________________
INPUT
the user's account number : The account number that the program is seraching for (user input)
OUTPUT
valid/invalid : Whether or not the number that is inputted is in the array
_______________________________________________________________________________
*******************************************************************************
*/
//
#include <iostream>
using namespace std;
//a binary search function to help look for the user inputted value
int binary(int arr[], int num, int SIZE)
{
int firstPos = 0; //the first position in the array
int lastPos = SIZE - 1; //the last position of the array
int middlePos; //the middle position of the array
int position = -1; //the position of the inputted value
bool found = false; //a boolean flag
//search for the value
while (!found && firstPos <= lastPos)
{
middlePos = (firstPos + lastPos) / 2;
if(arr[middlePos] == num)
{
found = true;
position = middlePos;
}
else if(arr[middlePos] > num)
{
lastPos = middlePos - 1;
}
else
{
firstPos = middlePos + 1;
}
//return the position of the value
return position;
}
return 0;
}
//a selection sort which helps to sort the array of account numbers
void selectionSort(int arr[], int SIZE)
{
int start; //the starting position
int minInd; //the index of the minimum value
int minVal; //the value of the smallest number
//sort through the array
for(start = 0; start < (SIZE - 1); start++)
{
minInd = start;
minVal = arr[start];
for(int index = start + 1; index < SIZE; index++)
{
if(arr[index] < minVal)
{
minVal = arr[index];
minInd = index;
}
}
arr[minInd] = arr[start];
arr[start] = minVal;
}
}
int main() {
//Data Dictionary
int userAccNum; //INPUT the user's account number
int SIZE = 18; //CONSTANT the size of the array
//INPUT the array that contains all of the account numbers
int accNumArray[SIZE] = {5658845, 4520125 , 7895122 , 8777541 , 8451277, 1302850, 8080152, 4562555, 5552012, 5050552, 7825877, 1250255, 1005231, 6545231, 3852085, 7576651, 7881200, 4581002};
//Ask the user for the input (account number)
cout << "Please enter the user number you are looking for." << endl;
cin >> userAccNum;
//Sort the list of account numbers in ascending order
selectionSort(accNumArray, SIZE);
//Implement a binary search to look for the number
//Output whether or not the number was found
cout << binary(accNumArray, userAccNum, SIZE) << endl;
return 0;
}