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
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
70
71
72
73
74
75
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <vector>
#include <fstream>
#include <bitset>
using namespace std;

int binarySearch(int, vector<int>, int);
void selectionSort(int, vector<int>);
int linearSearch(int, vector<int>, int);
void store_data(int, vector<int>);

int main()
{
	int n, x, y, z; vector<int> data;
	cout << "Enter n (number of inputs): "; cin >> n;
	cout << "Enter numbers...\n";
	for(int i = 0; i < n; i++)
	{
		cout << "> "; cin >> x;
		data.push_back(x);
	}
	selectionSort(n, data);
	cout << "search number: "; cin >> y;
	z = binarySearch(n, data, y);
	if(z == -1)
		cout << "value not found";
	else
		cout << "value found! POS: " << (z+1) << endl;
		
	return 0;
}
int binarySearch(int n, vector<int>data_1, int value)
{
	int position = -1; bool found = false;
	int first = 0, middle, last = n-1;
	while(first <= last && !found)
	{
		middle = (first+last)/2;
		if(data_1[middle] == value)
		{
			found = true;
			position = middle;
		}
		else if(data_1[middle] > value)
			last = middle-1;
		else
			first = middle+1;
	}
	return position;
}
void selectionSort(int n, vector<int>data_1)
{
	int mI, mV;
	for(int i = 0; i < n-1; i++)
	{
		mI = i;
		mV = data_1[i];
		for(int j = i+1; j < n; j++)
		{
			if(data_1[j] < mV)
			{
				mV = data_1[j];
				mI = j;
			}
		}
		data_1[mI] = data_1[i];
		data_1[i] = mV;
	}
	for(int i = 0; i < n; i++)
		cout << data_1[i] << endl;
}


Enter n (number of inputs): 3
Enter numbers...
> 1
> 7
> 0
0
1
7
search number: 0
value not found
--------------------------------
Process exited after 7.293 seconds with return value 0
Press any key to continue . . .

The vector is sorted and the binary search code is correct.
Why is 0 unable to be found???
Ignore the other preprocessor directives.
Last edited on
The vector is sorted
A vector does get sorted, but not the one you think. Since you're passing the vector to selectionSort by value, you actually make a copy of the vector, sort the copy, then throw the copy away when the function returns. Try passing the vector by reference to your selectionSort function.
Okay got it. Thanks.
Topic archived. No new replies allowed.