how to you do a comparison count?

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void BinarySearch (ItemType& item, bool& found)
{
	int midPoint;
	int first = 0;
	int last = list.length-1;
	bool  moreToSearch = first <= last;
	found = false;


	while (moreToSearch && !found)
	{
		 midPoint = (first + last) / 2;
  
	if (item.number < list.info[midPoint].number)
	{
		 last = midPoint - 1;
		 moreToSearch = first <= last;
	}
	else if (item.number > list.info[midPoint].number) 
	{
		first = midPoint +1;
		moreToSearch = first <= last;
	}
	 else 
	{
		item = list.info[midPoint];
		found = true;
	}
 } 

}
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.
ok but where would i put count++ into the BinarySearch() method above?
closed account (D80DSL3A)
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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;
	}
	else if (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;
	}
 } 

}

Is this what you meant?
ya i think thats right
thanks for the help
Topic archived. No new replies allowed.