mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-26 13:06:07 +00:00
完善所以c#相关的文档和代码
This commit is contained in:
@@ -173,7 +173,25 @@ $$
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_search.cs"
|
||||
|
||||
/* 二分查找(双闭区间) */
|
||||
int binarySearch(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;
|
||||
}
|
||||
```
|
||||
|
||||
### “左闭右开”实现
|
||||
@@ -303,7 +321,25 @@ $$
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_search.cs"
|
||||
|
||||
/* 二分查找(左闭右开) */
|
||||
int binarySearch1(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;
|
||||
}
|
||||
```
|
||||
|
||||
### 两种表示对比
|
||||
@@ -383,7 +419,10 @@ $$
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
// (i + j) 有可能超出 int 的取值范围
|
||||
int m = (i + j) / 2;
|
||||
// 更换为此写法则不会越界
|
||||
int m = i + (j - i) / 2;
|
||||
```
|
||||
|
||||
## 复杂度分析
|
||||
|
||||
Reference in New Issue
Block a user