mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 12:56:29 +08:00
Fixed format of doc
This commit is contained in:
parent
6264edcadb
commit
e0d3572a47
1 changed files with 11 additions and 11 deletions
|
@ -161,18 +161,18 @@ $$
|
|||
=== "TypeScript"
|
||||
|
||||
```typescript title="binary_search.ts"
|
||||
/* 二分查找(左闭右开) */
|
||||
const binarySearch1 = function (nums: number[], target: number): number {
|
||||
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
|
||||
let i = 0, j = nums.length;
|
||||
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
|
||||
while (i < j) {
|
||||
let m = Math.floor(i + (j - i) / 2); // 计算中点索引 m
|
||||
if (nums[m] < target) { // 此情况说明 target 在区间 [m+1, j) 中
|
||||
/* 二分查找(双闭区间) */
|
||||
const binarySearch = function (nums: number[], target: number): number {
|
||||
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
|
||||
let i = 0, j = nums.length - 1;
|
||||
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
|
||||
while (i <= j) {
|
||||
let m = Math.floor(i + (j - i) / 2);// 计算中点索引 m
|
||||
if (nums[m] < target) { // 此情况说明 target 在区间 [m+1, j] 中
|
||||
i = m + 1;
|
||||
} else if (nums[m] > target) { // 此情况说明 target 在区间 [i, m) 中
|
||||
j = m;
|
||||
} else { // 找到目标元素,返回其索引
|
||||
} else if (nums[m] > target) { // 此情况说明 target 在区间 [i, m-1] 中
|
||||
j = m - 1;
|
||||
} else { // 找到目标元素,返回其索引
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue