Adding Binary Search

So the program I have for homework lists the values I have in an array in increasing order. I am having trouble with adding binary search to it. I also need to be able to prompt the user to enter values to search. This is my code currently.

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
#include <iostream>
#include <vector> // for use of vectors
#include <fstream> // for opening the test file
#include <algorithm> // for use of swap

using namespace std;

main (int argc, char const *argv[])
{
	const int size = 8;
	int array[size] = {20, 10, 5, 15, 35, 40, 25, 30};

	fstream in;
	in.open(argv[1]);

	for (int element = 0; element < size; ++element)
	{
		int smallElement = element;

		for (int currentElement = element + 1; currentElement < size; ++currentElement)
		{
			if(array[currentElement] < array[smallElement])
			smallElement = currentElement;
		}
		swap(array[element], array[smallElement]);
	}
	for (int index = 0; index < size; ++index)
	cout << array[index] << " " << endl;

	return 0;
}


The binary search example I was given was this:
1
2
3
4
5
6
7
8
9
10
11
	int binary_search(vector<int> v, int from, int to, int value)
	{
		if (from > to)
			return -1;
		int mid = (from + to) / 2;
		if(v[mid] == value)
			return mid;
		else if (v[mid] < value)
			return binary_search(v, mid + 1, to, value);
		else
			return binary_search(v, mid - 1, value)
;

The end goal is to for the user to enter the values:

1, 15, 18, 40, 30, 50, ctrl+D(to end the input)

And the output from the program should be:

-1, 2, -1, 7, 5, -1
Last edited on
Line 11 in binary search code: You are passing 3 parameters, when the function expects 4.
Topic archived. No new replies allowed.