How to fix this error ( binary search)

Hello all pro. I write this program by visual studio C++ 2010
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#ifndef BinarySearch_H
#define BinarySearch_H
#define max 1000
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
class binarySearch
{
private:
	int length;
	int ARRAY[max];
public:
	binarySearch();
	binarySearch(int );
	void RandomGeneratorNumber();
	int returnLength();
	int bSearch(int );
	
	void PrintARRAY();
};
binarySearch::binarySearch()
{
	length = 0;
}
binarySearch::binarySearch(int sopt)
{
	length = sopt; 
}
int binarySearch::returnLength()
{
	return length;
}
void binarySearch::RandomGeneratorNumber()
{
	srand(time(0));
	for(int i = 0; i<= length; i++)
		ARRAY[i] = rand()%length;
}
int binarySearch::bSearch(int _needSearch)
{
	bool co = false;
	int MIN = 0;
	int MAX = length - 1;
	int MID;
	while(MIN <= MAX )
	{
		MID = (MIN+MAX)/2;
		if(ARRAY[MID] == _needSearch)
		{
			co = true;
			break;
		}
		else if(ARRAY[MID] > _needSearch)
			MAX = MID - 1;
		else
			MIN = MID + 1;
	}
	if(co == true)
		return MID;
	else
		return -1;
}
void binarySearch::PrintARRAY()
{
	for(int i = 0; i < length; i++)
		cout<<ARRAY[i]<<";";
}
#endif 

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "BinarySearch.h"
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
	binarySearch a(5);
	srand(time(0));
	a.RandomGeneratorNumber();
	a.PrintARRAY();
	cout<<endl;
	cout<<a.bSearch(22)<<endl;
	system("pause");
	return 0;
}

Thanks for helping !
You don't state what the error is.

I can see a few. For one thing, the array is populated with values in the range 0 to 4, therefore a value of 22 will never be found. More important, a binary search only works on data which is sorted into key sequence. Since the data is random, a binary search is not applicable unless you first sort the data.

A couple of other points. You call srand() in both main() and RandomGeneratorNumber() which is not necessary. Normally you call srand just once at the start.

The loop at line 37 executes too many times:
for(int i = 0; i<= length; i++)
should be i<length

The constructor does not check whether sopt is bigger than max, it should or the program could attempt to access data outside the bounds of the array.

It is better to use const int max = 1000; rather than #define

It is also best to avoid putting using namespace std; inside header files, as it forces that upon whichever file includes the header whether it is wanted or not.


Thanks for helping. Have a nice day to you! Chervil
Topic archived. No new replies allowed.