What is wrong with this binary search algorithm

Hello, I have currently written a code for the binary search algorithm. However, the code does not seem to be working when I input a vector of {2, 4, 3, 1}. Can someone please tell me what is wrong with this code? Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int binarySearch(vector<int> data, int target)
{
	int min = 0;
	int max = data.size() - 1;

	while (true)
	{
		int index = (min + max) / 2;
		if (data.at(index) == target)
		{
			return index;
		}
		else if (data.at(index) > target)
		{
			max = index - 1;
		}
		else
		{
			min = index + 1;
		}
	}
}
Last edited on
If the target isn't found ...
(1) You never stop looping; (fix the while condition);
(2) You don't return anything; (return -1 or similar)

Also...
(3) You need to sort your vector.
Thank you!! I forgot about all of those things... I'm such an idiot!!
Wait, when I am sorting my vector, I am trying to sort it using the quick sort algorithm.

So I have looked at the c++ code at the bottom of this website: http://www.algolist.net/Algorithms/Sorting/Quicksort

But since I am using vectors, I have modified the code to this:

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
#include <iostream>
#include <vector>

using namespace std;

void quickSort(vector<int> vec, int left, int right)
{
	int i = left;
	int j = right;
	int tmp;
	int pivot = vec.at((left + right) / 2);
	
	while (i <= j)
	{
		while (vec.at(i) < pivot)
		{
			i++;
		}
		while (vec.at(j) > pivot)
		{
			j--;
		}
		if (i <= j)
		{
			tmp = vec.at(i);
			vec.at(i) = vec.at(j);
			vec.at(j) = tmp;
			i++;
			j--;
		}
	}
	
	if (left < j)
	{
		quickSort(vec, left, j);
	}
	if (i < right)
	{
		quickSort(vec, i, right);
	}
}

int main()
{
	vector<int> data = { 1, 12, 5, 26, 7, 14, 3, 7, 2 };
	quickSort(data, 0, data.size() - 1);
	return 0;
}


Can someone please help me to fix this? Thanks.
One way to do it is to simply copy the C++ code from the website you linked. Don't change it. Then call it like this:
 
    quickSort(data.data(), 0, data.size() - 1);


Here: data.data() the first data is the name of your vector. The second is the member function data() which gives access to the values in the array just as though it was an ordinary array.

To use your own modified version of the code, you are currently passing the vector by value, which means it is working on a copy. You need to pass it by reference,
 
void quickSort(vector<int>& vec, int left, int right)
Note the &.

But easiest of all, include the header <algorithm>
and use std::sort
sort(data.begin(), data.end());


Topic archived. No new replies allowed.