add dart examples for chapter 1 and 2 (#209)

* add dart example for chapter 1

* add dart example for chapter 2
This commit is contained in:
N3-M3-S1S
2022-11-19 00:31:23 +03:00
committed by GitHub
parent cd38dc146d
commit b3a143a3ae
2 changed files with 54 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
void main() {
final myList = [1, 3, 5, 7, 9];
print(binarySearch(myList, 3));
print(binarySearch(myList, -1));
}
int? binarySearch(List<int> list, int item) {
int low = 0;
int high = list.length - 1;
while (low <= high) {
final mid = (low + high) ~/ 2;
final guess = list[mid];
if (guess == item) {
return mid;
}
if (guess > item) {
high = mid - 1;
} else {
low = mid + 1;
}
}
}