userrandomnums - 1 year ago 54

C Question

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;

}

Answer Source

```
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`

).