[英]Dart binary search function is not working
This is my function and it always returns -1.这是我的 function,它总是返回 -1。 It prints right value of mid, but never returns it.它打印正确的中间值,但从不返回它。
int binarySearch(List<int> arr, int userValue, int min, int max) {
if (min >= 0) {
int mid = ((max + min) / 2).floor();
if (userValue == arr[mid]) {
print(mid);
return mid;
} else if (userValue > arr[mid]) {
binarySearch(arr, userValue, mid + 1, max);
} else {
binarySearch(arr, userValue, min, mid - 1);
}
}
return -1;
}
Usage of function function的使用
int result = binarySearch(dates, 22, 0, 30);
Binarysearch function二进制搜索 function
void Binarysearch(
List list,
int value,
int min,
int max
)
Implementation执行
void Binarysearch(List list, int value, int min, int max)
{
if(min > max) // Checking the list size with min and max
{
return null;
}
int mid = (max + min) ~/ 2; // taking the mid value using min and max values of the list
if(value < list[mid]) // Checking the given value is lessthen the mid value
{
return Binarysearch(list, value, min, mid - 1); // ittarating the search method untill value is find
}
else if(value > list[mid]) // Checking the given value is greaterthen the mid value
{
return Binarysearch(list, value, mid + 1, max); //ittarating the search method untill value is find
}
else
{
print("The $value is find at possition :$mid"); // finaly return the value
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.