我有一个数组A{1,2,3,4,5,6,7,8,9},给定一个数B=3.789,如何从数组A中快速找出与B最接近的数字!关键找的要快!应为数组A中的数可能很多,一定要以最快的方式找出来!
如何计算?
如何计算?
解决方案 »
- C# winForm中怎样给oracle数据库传进一个dataTable集合
- 向各位高手请教一个.net中的问题
- 请问Controls索引
- 关于C# winform 打包成DLL的问题
- 急急!!!无法加载 DLL“xxx_dll” 找不到指定的模块。 (异常来自 HRESULT0x8007007E)
- datagrid 加入了一个Image 类型的模板列,为什么总提示Image不是明确的引用
- 用socket做icmp 使用receivefrom()读不到数据?
- 中文字符的字节数问题
- 引用PDF打印机打印只打印出A4 纸其他幅面都打印不了。
- c# 这门垃圾语言,为什么微软不提供js脚本的执行
- 控制richtextbox中的图片大小
- 关于用C#创建系统帐户的问题
然后用对分查找,参考如下代码:
private int BinarySearch(double[] array, double value)
{
if (array == null || array.Length <= 0) return -1;
int low = 0;
int hi = array.Length - 1;
while (low <= hi)
{
int m = low + ((hi - low) >> 1); // 中间值
if (value > array[m])
low = m + 1;
else hi = m - 1;
}
low = Math.Min(low, array.Length - 1);
if (low <= 0) return low;
else return value - array[low - 1] < array[low] - value ? low - 1 : low;
}private void button1_Click(object sender)
{
double[] A = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//Array.Sort(A);//初始化,之后可以顺序插入
double[] B = { 1, 2, 2.5, 3.51, 3.49, 9, 100};
for (int i = 0; i < B.Length; i++)
{
int j = BinarySearch(A, B[i]);
Console.WriteLine("B={0},Index:{1},Value:{2}", B[i], j, j < 0 ? -1 : A[j]);
}
}---输出----
B=1,Index:0,Value:1
B=2,Index:1,Value:2
B=2.5,Index:2,Value:3
B=3.51,Index:3,Value:4
B=3.49,Index:2,Value:3
B=9,Index:8,Value:9
B=100,Index:8,Value:9
double[] A = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//Array.Sort(A);//初始化,之后可以顺序插入
double[] B = { 1, 2, 2.5, 3.51, 3.49, 9, 100};
for (int i = 0; i < B.Length; i++)
{
IEnumerable<double> query =
from student in A
orderby Math.Abs(student - B[i])
select student;
Console.WriteLine("B={0},Value:{1}", B[i], query.First<double>());
}---输出----
B=1,Value:1
B=2,Value:2
B=2.5,Value:2
B=3.51,Value:4
B=3.49,Value:3
B=9,Value:9
B=100,Value:9