Last active
October 15, 2023 06:25
-
-
Save myesn/c3a0d302a35d00ff114b340e465a707d to your computer and use it in GitHub Desktop.
在一维数组中使用二分查找算法得到目标值的索引
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int[] array = { 1,11,21,31,41 }; | |
foreach(int num in array) { | |
Console.WriteLine(BinarySearchMatrix(array, num)); | |
} | |
// 二分查找:在一维数组中找到目标值的索引 | |
int BinarySearch(int[] array,int target) | |
{ | |
// 初始化指针,定义头指针 left、尾指针 right = 二维数组中一维数组的数量-1=4-1,双闭区间 [0, array.Length - 1] | |
int left = 0, right = array.Length - 1; | |
// 双闭区间-循环终止条件:当头索引大于尾索引 | |
while (left <= right) | |
{ | |
// 计算中点 | |
var middle = left + (right - left) / 2; | |
if (array[middle] > target) | |
{ | |
// 中点值大于目标值,说明目标值在中点值左边,这时将右边界移动至中点-1 | |
right = middle - 1; | |
} | |
else if (array[middle] < target) | |
{ | |
// 中点值小于目标值,说明目标值在中点值右边,这时将左边界移动至中点+1 | |
left = middle + 1; | |
} | |
else | |
{ | |
return middle; | |
} | |
} | |
// 没有找到 | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment