### 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.

 ``12345678910111213141516171819202122`` ``````int binarySearch(vector 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:

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748`` ``````#include #include using namespace std; void quickSort(vector 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 data = { 1, 12, 5, 26, 7, 14, 3, 7, 2 }; quickSort(data, 0, data.size() - 1); return 0; }``````

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& 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.