userrandomnums - 7 months ago 38
C Question

# Why does my binary search only work with if statements in this order?

I'm wondering why my binary search code doesn't work with this code (it returns everything as found):

``````int BinarySearch(int arr[], int len, int target) {
int first = 0;
int last = len-1;
int mid = (first+last)/2;
while (first <= last) {
mid = floor((first+last)/2);
if (target = arr[mid]) {
return 1;
} else if (target < arr[mid]) {
last = mid-1;
} else {
first = mid+1;
}
}
return -1;
}
``````

But the following works. The only difference is the order of if statements in the while loop.

``````int BinarySearch(int arr[], int len, int target) {
int first = 0;
int last = len-1;
int mid = (first+last)/2;
while (first <= last) {
mid = floor((first+last)/2);
if (arr[mid] < target) {
first = mid+1;
} else if (target = arr[mid]) {
return 1;
}
else { //arr[mid] < target
last = mid-1;
}
}
return -1;
}
``````

``````if (target = arr[mid])
This is an assignment, not just a comparison. It will make `target` be equal to `arr[mid]` (and then enter the block, unless the value is `0`).