So I am working with arrays and the idea is that the function finds the element in the array (I need to test this function taken out of a larger program)of the value that is specified in "item". When the value is within the input file range, (the input file I am using has 20 integers) the function is supposed to cout the specified parameters: Either the number is not found in the array or the number is found at element ____ , and the number of comparisons made.
My problem is when I enter a number larger than the file holds, say 25 if the file has 1-20, then the cout is supposed to show the maximum comparisons but instead it is just printing 0 for comparisons.
I need it to show all comparisons even if the number is not contained in the file.
Thanks for any help.
#include <iostream>
#include <fstream>
using namespace std;
int sCount;//Global variable for sequential search comparisons.
int bsCount;//Global variable for binary search comparisons.
int search(int A[], int lo, int hi, int item)
{
int index = lo; //Used as a subscript to search array.
int position = -1; //To record position of search value.
bool found = false; //Flag to indicate if the value was found.
while(index < hi && !found)
{
if(A[index] == item) //If the value is found.
{
found = true; //Set the flag.
position = index; //Record the values subscript.
}
index++; //Go to the next element.
sCount++;
}
return position; //Return the position or -1.
}
cout << itemsread << " Numbers were read from " << inputfile << endl;//Prints items read from input*/
int lo= 0; int hi = itemsread - 1;
/*itemsdisplay= display(A, lo, hi, out_file);//Function 2 call
itemsdisplay= display(A, lo, hi, cout);
cout << itemsdisplay << " Numbers were written to file " << outputfile << endl;//Prints items read from input*/
//////////////////////////////////////////////////////////////////////////////
//search goes where item is
results= search(A, lo, hi, item);
if (results == -1)
cout << "That number is not found in the array.";
cout << "That number is found at element " << (results + 1) << " of the array via linear search." << endl;
cout << "Comparisons made with sequential search: " << sCount << endl;
///////////////////////////////////////////////////////////////////////////////
//search goes where item is
/*binResults= binSearch(A, lo, hi, item);
if (binResults == -1)
cout << "That number is not found in the array.";
else
{
cout << "That number is found at element " << (binResults + 1) << " of the array via binary search." << endl;
cout << "Comparisons made with binary search: "<< bsCount << endl;*/