问题是元素的上限。当等于key时,算法返回-1;当大于key时,返回最高索引。
我的任务是在数组中不存在元素时返回-1。
算法:
public static int BinarySearch(int[] arr, int low, int high, int key)
{
if(high<low)
{
return low - 1;
}
int mid = low + ((high - low) / 2);
//this 'if' is my solution when key is more than high bound element
if (mid == high)
{
if (arr[mid] != key)
{
return -1;
}
}
if (arr[mid] == key)
{
return mid;
}
else if (arr[mid] < key)
{
return BinarySearch(arr, mid + 1, high, key);
}
else
{
return BinarySearch(arr, low, mid - 1, key);
}
}
驱动程序代码:
static void Main(string[] args)
{
string[] arr = Console.ReadLine().Split(' ');
int[] n = new int[Convert.ToInt32(arr[0])];
for(int i =1;i<Convert.ToInt32(arr[0]);i++)
{
n[i-1] = Convert.ToInt32(arr[i]);
}
string[] arr2 = Console.ReadLine().Split(' ');
int[] k = new int[Convert.ToInt32(arr2[0])];
for(int i = 1; i< Convert.ToInt32(arr2[0]);i++)
{
k[i-1] = Convert.ToInt32(arr2[i]);
}
int[] answer = new int[Convert.ToInt32(arr2[0])];
for(int i = 0;i< Convert.ToInt32(arr[0]);i++)
{
answer[i] = BinarySearch(n, 0, n.Length - 1 , k[i]);
}
for (int i = 0; i < Convert.ToInt32(arr[0]); i++)
{
Console.Write(answer[i]+" ");
}
}
输入:
first line: 5 1 2 3 4 5
second line: 5 1 2 3 4 5
it should return : 0 1 2 3 4
mine returned: 0 1 2 3 -1
任何帮助将不胜感激。