flutter 如何实现dart二分查找算法?

jei2mxaa  于 2023-01-18  发布在  Flutter
关注(0)|答案(3)|浏览(197)

如何在dart主函数中使用二分查找算法?

int binarySearch<T>(List<T> sortedList, T value,{int Function(T, T)? compare}) {
 compare ??= defaultCompare(); // I do not understand this line code
 var min = 0;
 var max = sortedList.length;
 while (min < max) {
   var mid = min + ((max - min) >> 1);
   var element = sortedList[mid];
   var comp = compare(element, value); // I do not understand this line code 
   if (comp == 0) return mid;
   if (comp < 0) {
     min = mid + 1;
   } else {
     max = mid;
   }
 }
 return -1;
}

为什么使用这行代码?

{int Function(T, T)? compare} 
compare ??= defaultCompare(); 
var comp = compare(element, value);
vddsk6oq

vddsk6oq1#

??=是可识别空值的赋值运算符。https://dart.dev/guides/language/language-tour#assignment-operators
代码应该读取compare ??= defaultCompare;,这意味着,如果变量comparenull,则“撕下”函数defaultCompare并将其赋给变量compare
在dart中,函数是一个对象,可以存储在变量中。https://dart.dev/guides/language/language-tour#functions-as-first-class-objects
var comp = compare(element, value);调用变量compare中的函数,并将结果赋给新变量comp

soat7uwm

soat7uwm2#

在'package:flutter/foundation. dart'中有一个内置函数binarySearch()。你可以在main中使用这个函数,而不用从头开始写。

wvmv3b1j

wvmv3b1j3#

int? binarySearch(List list, int item) {
int low = 0;
int high = list.length;
while (low <= high) {
int mid = ((low + high) / 2).floor();
int guess = list[mid];
if (guess == item) {
  return guess;
} else if (guess > item) {
  high = mid - 1;
} else {
  low = mid + 1;
}
}
return null;
}

相关问题