i need to include a comparison count in this BinarySearch() method to count the number of comparisons required to find a student given a student number.
not sure how to code the comparison count but i got the BinarySearch() method working
i basically need to output how many times the BinarySearch() method searchs a text file for the correct student number
add int count = 0 in the beginning and then place count++ anywhere where you want it to increment one or cout, ofstream, or whatever method you want to use to see the count, I personally like ofstream in the form of a log file. I created a library for Logging data so I could log at certain spots what is going on. this is great for Windows programs where there is no console to view, you just view the log file and see what is going on and what location.
Comparisons are made on lines 14 and 19.
If the code following the if statement is executed then 1 comparison has been made.
If the code following the if else statement is executed then 2 comparisons have been made.
If the code following the last else statement is executed then 2 comparisons have been made.
So maybe:
void BinarySearch (ItemType& item, bool& found, int& compCount)// 3rd arg. added
{
int midPoint;
int first = 0;
int last = list.length-1;
bool moreToSearch = first <= last;
found = false;
compCount = 0;// new line
while (moreToSearch && !found)
{
midPoint = (first + last) / 2;
if (item.number < list.info[midPoint].number)
{
compCount += 1;// new line
last = midPoint - 1;
moreToSearch = first <= last;
}
elseif (item.number > list.info[midPoint].number)
{
compCount += 2;// new line
first = midPoint +1;
moreToSearch = first <= last;
}
else
{
compCount += 2;// new line
item = list.info[midPoint];
found = true;
}
}
}