Function won't accept value of variable?

This is the weirdest issue I've had. This is a recursive binary search function.


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


void vBinarySearch(int iEnd, int iStart, int iFind, int iArray[], int &iLoc)
{
	iLoc = -1;
	while (iEnd>=iStart)
	{
		if (iArray[(iEnd + iStart) / 2] == iFind)
		{
			iLoc = (iEnd + iStart) / 2;
		}
		else if (iArray[(iEnd + iStart) / 2] > iFind)
		{
			vBinarySearch(((iEnd + iStart) / 2) - 1, iStart, iFind, iArray, iLoc);
		}
		else
		{
			vBinarySearch(iEnd, ((iEnd + iStart) / 2) + 1, iFind, iArray, iLoc);
		}

	}
	
}

int main()
{
	

	int iArray[5] = { 1,2,3,4,5 };
	int iFind = 2;
	int iLoc = 0;
	vBinarySearch(5 - 1, 0, iFind, iArray,iLoc);
	std::cout << iLoc;
	


	system("pause");
	return 0;
}

  




Here is my code. So if you run it, initially iStart will be 0 and iEnd will be 4.

Next round it will see that the middle value (3) is bigger than 2 so it will do option 2, and change iEnd to be the middle value (3) negative one, so 2.

Second round it will have iStart still be 0, iEnd =2, and then it will check the middle value (now 1) is smaller than 2, so it will want to change iStart to be middle value plus one (so change to 2)

But here is the issue. IT DOESNT. For some reason, it refuses to change iStart! Its just stuck on 0!

any clue why this is happening? is it just from my computer or what? My code looks like theres no logical error....
Well having a while loop with an invariant exit condition (you never change any of the values) is a problem.
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
(gdb) bt
#0  vBinarySearch (iEnd=1, iStart=1, iFind=2, iArray=0x7fffffffde40, iLoc=@0x7fffffffde38: -1) at main.cpp:7
#1  0x00000000004008af in vBinarySearch (iEnd=1, iStart=0, iFind=2, iArray=0x7fffffffde40, iLoc=@0x7fffffffde38: -1) at main.cpp:20
#2  0x000000000040087e in vBinarySearch (iEnd=4, iStart=0, iFind=2, iArray=0x7fffffffde40, iLoc=@0x7fffffffde38: -1) at main.cpp:16
#3  0x0000000000400921 in main () at main.cpp:34
(gdb) s
8		while (iEnd>=iStart)
(gdb) 
10			if (iArray[(iEnd + iStart) / 2] == iFind)
(gdb) 
12				iLoc = (iEnd + iStart) / 2;
(gdb) 
8		while (iEnd>=iStart)
(gdb) 
10			if (iArray[(iEnd + iStart) / 2] == iFind)
(gdb) 
12				iLoc = (iEnd + iStart) / 2;
(gdb) 
8		while (iEnd>=iStart)
(gdb) 
10			if (iArray[(iEnd + iStart) / 2] == iFind)
(gdb) 
12				iLoc = (iEnd + iStart) / 2;
(gdb) 
8		while (iEnd>=iStart)
(gdb) 
Simply remove the while loop.
Oh wow, yeah just changed while() to if() and its fixed. thanks guys
Topic archived. No new replies allowed.