As my question is titled, I would appreciate help with my binary search, shown below. Currently, the search will always return false. I am almost certain that my sorting algorithm is correct, as it worked perfectly while temporarily implementing a linear search. I have seen lots of other questions with similar problems as mine, yet I cannot spot the error in my code.
#include <cs50.h>
#include <stdio.h>
#include "helpers.h"
/**
* Returns true if value is in array of n values, else false.
*/
bool search(int value, int values[], int n)
{
//TODO: implement a searching algorithm
int counter1 = 0;
int counter2 = n - 1;
while (counter2 >= counter1)
{
int counter3 = (counter1 + counter2) / 2;
if (values[counter3] == value)
{
return true;
}
else if (values[counter3] > value)
{
//search left
counter2 = counter3 - 1;
}
else if (values[counter3] < value)
{
//search right
counter1 = counter3 + 1;
}
}
return false;
}
Here's my sort, just in case:
void sort(int values[], int n)
{
int EXIT = 0;
int counter3 = -1;
while (EXIT == 0)
{
int counter1 = -1;
int counter2 = 0;
int counter4 = 0;
counter3++;
while (counter1 < n - counter3 && counter2 < n - counter3)
{
counter1++;
counter2++;
if (values[counter1] < values[counter2])
{
int array_temp[1] = {0};
array_temp[0] = values[counter1];
values[counter1] = values[counter2];
values[counter2] = array_temp[0];
counter4++;
}
}
if (counter4 == 0)
EXIT++;
}
return;
}