I was writing up code for a binary search algorithm.
Code:
#include "cs50.h"
int main(void) {
int n = GetInt();
int value = GetInt();
int values[n];
for (int i = 0; i < n; i++) {
printf("Put in number %i ", i + 1);
values[i] = GetInt();
}
int mid = (n - 1) / 2;
int en = 0;
int ex = n - 1;
for (int i = 0, xt = i + 1; i < xt; i++) {
if (value > values[mid]) {
en = mid;
mid = (en + ex) / 2;
}
else if (value < values[mid]) {
ex = mid;
mid = (en + ex) / 2;
}
else if (value == values[mid]) {
printf("found");
break;
} else {
printf("not found");
break;
}
}
}
But it only works when the value to be found is somewhere in the middle.
It fails when :
- value to be found is first or last.
- value to be found is not in the values inputted.
I really cannot figure out the mistake.