c# – BinarySearch如何在两个邻居之间找到数组中的值?
发布时间:2020-12-16 00:06:55 所属栏目:百科 来源:网络整理
导读:我有一个排序数组double. 目标是在Array中查找索引. 其中包含 =搜索值的值. 例如,数组包含数字{0,5,12,34,100},索引范围为[0 .. 4]. 搜索值= 25.我想得到指数= 2(出现的范围在12到34之间) 我不明白在这种情况下如何运行二进制搜索. public class MyComparer
我有一个排序数组double.
目标是在Array中查找索引. 其中包含< =搜索值的值. 例如,数组包含数字{0,5,12,34,100},索引范围为[0 .. 4]. 搜索值= 25.我想得到指数= 2(出现的范围在12到34之间) 我不明白在这种情况下如何运行二进制搜索. public class MyComparer : IComparer<double> { public int Compare(double x,double y) { //<-------- ??? } } public double[] spline_x; MyComparer cmpc = new MyComparer(); int i=Array.BinarySearch(spline_x,x,cmpc); 解决方法
当二进制搜索没有在数组中找到项时,它返回一个负数,它是第一个元素的索引的位数补码,它大于value.以下是使用它来查找范围的方法:
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 } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |