feat: add chapter_binary_search by dart (#506)

* feat: add chapter_sorting by dart

* feat: add chapter_searching by dart

* feat: add chapter_binary_search by dart

---------

Co-authored-by: huangjianqing <huangjianqing@52tt.com>
pull/508/head
Jefferson Huang 2 years ago committed by GitHub
parent 399e5df39a
commit 921d87c238
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,63 @@
/**
* File: binary_search.dart
* Created Time: 2023-05-12
* Author: Jefferson (JeffersonHuang77@gmail.com)
*/
/* 二分查找(双闭区间) */
int binarySearch(List<int> nums, int target) {
// [0, n-1] i, j
int i = 0, j = nums.length - 1;
// i > j
while (i <= j) {
int m = (i + j) ~/ 2; // m
if (nums[m] < target) {
// target [m+1, j]
i = m + 1;
} else if (nums[m] > target) {
// target [i, m-1]
j = m - 1;
} else {
//
return m;
}
}
// -1
return -1;
}
/* 二分查找(左闭右开区间) */
int binarySearchLCRO(List<int> nums, int target) {
// [0, n) i, j +1
int i = 0, j = nums.length;
// i = j
while (i < j) {
int m = (i + j) ~/ 2; // m
if (nums[m] < target) {
// target [m+1, j)
i = m + 1;
} else if (nums[m] > target) {
// target [i, m)
j = m;
} else {
//
return m;
}
}
// -1
return -1;
}
/* Driver Code*/
void main() {
int target = 6;
final nums = [1, 3, 6, 8, 12, 15, 23, 67, 70, 92];
/* 二分查找 (双闭区间) */
int index = binarySearch(nums, target);
print('目标元素 6 的索引 = $index');
/* 二分查找(左闭右开区间) */
index = binarySearchLCRO(nums, target);
print('目标元素 6 的索引 = $index');
}
Loading…
Cancel
Save