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
).
if (target = arr[mid]) {
really? Do you mean ==
?
Just in addition to the answers mentioned, the =
operator assigns and then returns the value assigned if the assignment was successful. For eg. if you do printf("%d", (a = 10));
you will see 10
printed. So, when you use the assignment operator in a if
statement, it boils down to something like if (10)
(or some other number) and thus your if
block gets executed. I hope it is obvious why if (a = 0)
wont get you to execute the if
block. HTH.
if (target = arr[mid])
this is wrong as it assigns a value to target and apparently you want to compare, so do this
if (target == arr[mid])
use the double ==
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.