Binary search

The following code supposedly worked in my school lab (in Turbo C++), but at home (in Dev C++) it doesn't seem to do that same. The program is for Binary search.

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
36
37
38
39
40
41
42
43
  #include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;

int main()
{
	float a[10],p;
	int i,top,bot,mid;
	cout<<"Type the numbers in ascending order: \n";
	
	for(i=0;i<10;i++)
	{
		cin>>a[i];
	}
	top=0;bot=9;
	
	cout<<"Type the number you want to search:  ";
	cin>>p;
	mid=(top+bot)/2;
	
	while((top<=bot)&&(a[mid]=!p))
	{
		if(p<a[mid])
		{
			bot=mid-1;
		}
		else
		{
			top=mid+1;
		}
		mid=(top+bot)/2;			
	}
	
	if(a[mid]==p)
	{
		cout<<"The number is at position:   "<<mid+1<<endl;
	}
	else
	{
		cout<<"The number wasn't found.";
	}
}



Type the numbers in ascending order:
1
2
3
4
5
6
7
8
9
10
Type the number you want to search:  5
The number wasn't found.
You should use a debugger and step through your while loop, line by line, to see where logic starts to go awry.

Did you really mean to do this? a[mid]=!p
Did you mean !=?
Last edited on
You are an absolute godsend. BTW, I am still in Highschool, and they don't teach us how to use Dev C++, insisting on using Turbo. They also haven't told us how to use a Debugger. Can you explain a bit to me, or point me towards any video or article that does?
turbo should have a debugger, though the last time I used it was in 1994, so maybe my memory is wrong. should be a menu drop down 'debug'.
what you do is compile your code in debug mode, and launch the debugger from your tool. Then you can step through the code, line by line, and observe variables as they are changed by the code. You see something go wrong and fix it, eg for loop suppose to go 10 times, and you step and it starts loop # 11, you found a problem.

old school, you can also debug by using print statements. find places in your code to inject a print that tells you what is happening there, and run it. You can use the pre-processor to turn these off and on, or comment/ uncomment them as you work the code. Remove or leave them when done is your choice (some are useful if problems come up later, some were only useful while you were fixing a specific problem that is now fixed so don't need anymore).
Last edited on
Topic archived. No new replies allowed.