C# BinarySearch如何在两个相邻的数组中查找值?
我有一个排序数组double。 目标是在数组中查找索引。C# BinarySearch如何在两个相邻的数组中查找值?,c#,arrays,algorithm,find,binary-search,C#,Arrays,Algorithm,Find,Binary Search,我有一个排序数组double。 目标是在数组中查找索引。 它包含的值。当二进制搜索在数组中找不到项时,它返回一个负数,该负数是大于该值的第一个元素的索引的按位补码。以下是使用它查找范围的方法: double[] spline_x = { 0D, 5D, 12D, 34D, 100D }; int i = Array.BinarySearch(spline_x, 25); if (i >= 0) { // your number is in array } else { in
它包含的值。当二进制搜索在数组中找不到项时,它返回一个负数,该负数是大于该值的第一个元素的索引的按位补码。以下是使用它查找范围的方法:
double[] spline_x = { 0D, 5D, 12D, 34D, 100D };
int i = Array.BinarySearch(spline_x, 25);
if (i >= 0)
{
// your number is in array
}
else
{
int indexOfNearest = ~i;
if (indexOfNearest == spline_x.Length)
{
// number is greater that last item
}
else if (indexOfNearest == 0)
{
// number is less than first item
}
else
{
// number is between (indexOfNearest - 1) and indexOfNearest
}
}
不熟悉C#,但简单的二进制搜索就可以做到这一点,找到最后一个数字=end){
返回-1;
}
大小\u t mid=(开始+结束)/2;
如果(v[mid]>num){
//[mid,end]大于num,边界在[begin,mid]中
返回find_last(num、v、begin、mid);
}
//v[mid]是合格的,谢谢。我有点简化:int I=Array.BinarySearch(spline_x,x);如果(I=0){}@Mixer记住,在递减I之后,你可以得到数组最后一项的索引
-1
double[] spline_x = { 0D, 5D, 12D, 34D, 100D };
int i = Array.BinarySearch(spline_x, 25);
if (i >= 0)
{
// your number is in array
}
else
{
int indexOfNearest = ~i;
if (indexOfNearest == spline_x.Length)
{
// number is greater that last item
}
else if (indexOfNearest == 0)
{
// number is less than first item
}
else
{
// number is between (indexOfNearest - 1) and indexOfNearest
}
}
int find_last(int num, const vector<int>&v, size_t begin, size_t end) {
if (begin >= end) {
return -1;
}
size_t mid = (begin + end) / 2;
if (v[mid] > num) {
// [mid, end) is bigger than num, the boundary is in [begin, mid)
return find_last(num, v, begin, mid);
}
// v[mid] is qualified as <= N, search [mid+1, end) for
// approaching a better boundary if exists.
size_t index = find_last(num, v, mid+1, end);
return (index == -1 ? mid : index);
}