Binary search help

This is an account validation program using a binary search array.
When I enter any value it gives me the message:"Account number 12520255 is valid"
That's the second element in the array, i don't get why that shows for anything I enter.
Can anyone let me know what's wrong?
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
#include <iostream>

using namespace std;

bool binarySearch(long array[], int, int accNumber);


int main()
{
	long accounts[18] = {
		1005231, 1250255, 1302850,3852085, 4520125, 4562555,
		4581002, 5050552, 5552012,5658845, 6545231, 7576651,
		7825877, 7881200, 7895122, 8080152, 8451277, 8777541 };

	int accNumber, results;

	cout << "\n\tPlease enter a valid Account Number: ";
	cin >> accNumber;
	results = binarySearch(accounts, 18, accNumber);
	if (results == -1)
		cout << "\n\tAccount number is invalid.";
	else
		cout << "\n\tAccount number " << accounts[results] << " is valid.\n";

	return 0;
}

bool binarySearch(long array[], int SIZE, int accNumber)
{
	int first = 0;
	int	last = 18 - 1;
	int	position = -1;
	int middle;
	bool found = false;

	while (!found && first <= last)
	{
	    middle = (first + last) / 2;
		if (array[middle] == accNumber)
		{
			found = true;
			position = middle;
		}
		else if (array[middle] > accNumber)
			last = middle - 1;
		else
			first = middle + 1;
		}
		return position;

	}
Return type should be int if you're returning the position.
last should be initialized to size-1 (not a hardcoded 18-1).

You don't need the "found" flag or "position". Just return middle when you find the target, and return -1 after the loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
int bsrch(int *a, int size, int targ) {
    int first = 0, last = size - 1;
    while (first <= last) {
        int mid = (first + last) / 2;
        if (a[mid] == targ)
            return mid;
        if (a[mid] > targ)
            last = mid - 1;
        else
            first = mid + 1;
    }
    return -1;
}

Topic archived. No new replies allowed.