Binary search of string in array of objects

I need to search for a string in an array of objects, this is what I have but it does not seem to work, it always gives me the second string in the array instead of the one that i search for.

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
void binarySearch(Student S[], string name)
{

	int first = 0;
	int last = 9;
	int middle;
	int position = -1;
	bool found = false; 

	
	while(!found && first <last)
	{
		middle = (first + last)/2;
		if(S[middle].getName() == name)
		{
			found = true;
			position = middle;
		}
		else if (S[middle].getName() > name)
		{
			last = middle -1;
		}
		else
		{
			first = middle +1;
		}
	}
	
	cout<<position;
}
This looks like binary search - is your input array sorted?
yes it is sorted, here is the code as it looks when sorted...

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
void binarySearch(Student S[], string name)
{

	int first = 0;
	int last = 9;
	int middle;
	int position = -1;
	bool found = false; 

	//FIRST SORT THE OBJECTS SO THAT THEY CAN BE SEARCHED
	Student temp;
	bool swap;
	do
	{
	swap = false;
	for (int i = 0; i<(10-1);i++)
	{
		if(S[i].getName() > S[i+1].getName())
		{
			temp = S[i];
			S[i] = S[i+1];
			S[i +1] = temp;
			swap = true; 
		}
	}
	}while(swap);

	cout<<"Name                     Age     Average"<<endl;
	for (int i = 0; i<10; i++)
	{
		cout<<left<<setw(25)<<S[i].getName()<<setw(10)<<S[i].getAge()<<setw(10)<<S[i].getAvg()<<endl;
	}


	//NOW DO THE BINARY SEARCH
	while(!found && first <last)
	{
		middle = (first + last)/2;
		if(S[middle].getName() == name)
		{
			found = true;
			position = middle;
		}
		else if (S[middle].getName() > name)
		{
			last = middle -1;
		}
		else
		{
			first = middle +1;
		}
	}
	
	cout<<"Name                     Age     Average"<<endl;
	cout<<left<<setw(25)<<S[position].getName()<<setw(10)<<S[position].getAge()<<setw(10)<<S[position].getAvg()<<endl;
}


the sorting part works well
is it possible that middle should be a double instead of an int? since it derives from a division and therefore it contains decimal points.
Topic archived. No new replies allowed.