I'm writing a code about getting to know if the customer cards are inside the sorted list of cards of my cards.txt. The issue is that I do not find an error on my binarySearch function but it does not return me the "isFound". I tried a linear search it works perfectly, so here my binarySearch is the issue. What's wrong? What did I miss? Or maybe, is my version of C++, not the right one to use in that case? (I'm using C++98, on VSC)
#include <iostream> // preprocessor directive //
#include <fstream> // library for file (create/open/read)
#include <string>
usingnamespace std;
// linear Search which check if the name of frauder (customer) is inside the list of frauder
void search(int array[], int n, int x)
{
for (int i = 0; i < n; i++)
{
if (array[i] == x)
{
cout << "This credit card is inside the list" << endl;
}
}
}
//returns true if value is in list. assumes list sorted.
bool binarySearch(constint list[], int size, int value)
{
int first = 0, last = size - 1, middle;
bool isFound = false;
while (!isFound && first <= last)
{
middle = (first + last) / 2;
if (list[middle] == value)
isFound = true;
elseif (list[middle] > value) // lower half
last = middle - 1;
else
first = middle + 1; // upper half
}
return isFound;
}
int main()
{
constint numCards = 20;
ifstream readFile;
int cards[numCards], customerCard;
readFile.open("cards.txt");
// check if file exist
if (!readFile)
{
cout << "ERROR: Invalid filename\n";
return 1;
}
for (int i = 0; i < numCards && readFile >> cards[i]; i++)
{
cout << cards[i] << '\n';
}
readFile.close();
cout << "What credit card, would you like to use ? " << endl;
cin >> customerCard;
// search(cards, numCards, customerCard);
binarySearch(cards, numCards, customerCard);
return 0;
}
Compare your two functions.
- linear search has a cout, and returns void
- binary search has no cout and returns bool
> since I call the function correctly in the main
That's just it - you don't.
Well the call is correct, you're just not making any use of the bool result that comes back.
1 2 3 4 5 6 7 8 9 10 11 12 13
// linear Search which check if the name of frauder (customer) is inside the list of frauder
bool search(int array[], int n, int x)
{
for (int i = 0; i < n; i++)
{
if (array[i] == x)
{
// cout << "This credit card is inside the list" << endl;
returntrue;
}
}
returnfalse;
}
In main
1 2 3 4 5 6
if ( search(cards, numCards, customerCard) ) {
cout << "Yeah linear baby!" << endl;
}
if ( binarySearch(cards, numCards, customerCard) ) {
cout << "Yeah binary baby!" << endl;
}