Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
下面為 Example 1 解法
static void Main(string[] args)
{
BinarySearch();
}
private static void BinarySearch()
{
var nums = new int[] { -1, 0, 3, 5, 9, 12 };
int target = 9;
var result = BinarySearch(nums, target);
Console.WriteLine($"目標索引:{result}");
Console.ReadKey();
}
/// <summary>
/// 二分收詢
/// </summary>
/// <param name="nums">數組</param>
/// <param name="target">目標值</param>
/// <exception cref="NotImplementedException"></exception>
private static int BinarySearch(int[] nums, int target)
{
int left = 0;
int right = nums.Length - 1;
while (left <= right)
{
int mid = (right + left) / 2;
if (nums[mid] == target)
{
return mid;
}
else if (nums[mid] < target)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}