如下面代码,对二维数组进行折中查询,二维与折中都第一次用,不很了解,我直接把二维理解为一个datatable好了。查询结果为一个范围,即为第几行之第几行,(数组已排序)分别是字符串查询条件与整形查询条件,代码上标注了,循环位置有一点不同。我的理解是,整体架构完全不变,改变比较条件(无论类型),同一种搜索应该都可以适用才是,可是结果总是出现偏差,请高手看下
//字符串比较OK
string[,] arr = new string[24, 1];
arr[0, 0] = "A";
arr[1, 0] = "B";
arr[2, 0] = "B";
arr[3, 0] = "B";
arr[4, 0] = "C";
arr[5, 0] = "C";
arr[6, 0] = "C";
arr[7, 0] = "C";
arr[8, 0] = "C";
arr[9, 0] = "C";
arr[10, 0] = "D";
arr[11, 0] = "D";
arr[12, 0] = "D";
arr[13, 0] = "D";
arr[14, 0] = "D";
arr[15, 0] = "E";
arr[16, 0] = "E";
arr[17, 0] = "E";
arr[18, 0] = "F";
arr[19, 0] = "G";
arr[20, 0] = "G";
arr[21, 0] = "G";
arr[22, 0] = "S";
arr[23, 0] = "Z";
string IDNum = "B"; //查询字符串,动态改变值
int login = 0;
int end = arr.GetLength(0) - 1;
int half = (login + end) / 2;
string searNum = arr[half, 0];
while (login < end && !searNum.Equals(IDNum))
{
if (String.Compare(searNum, IDNum) < 0)
login = half + 1;
if (String.Compare(searNum, IDNum) > 0)
end = half - 1;
half = (login + end) / 2;
searNum = arr[half, 0];
}
int i = half;
while (searNum.Equals(IDNum) && i > 0)
{
i--;
login = i + 1;
if (login > end)
login = end;
if (i < 0) //区别位置
login = 0;
searNum = arr[i, 0];
}
int j = half;
searNum = arr[j, 0];
while (searNum.Equals(IDNum) && j < arr.GetLength(0) - 1)
{
j++;
end = j - 1;
if (login > end)
end = login;
if (j > arr.GetLength(0) - 1)
end = arr.GetLength(0) - 1;
searNum = arr[j, 0];
}
Console.WriteLine(login.ToString());
Console.WriteLine(end.ToString());
Console.ReadLine();
——————————————————————————————————————————
//数字比较OK
int[,] Arr = new int[24, 1];
Arr[0, 0] = 1;
Arr[1, 0] = 1;
Arr[2, 0] = 1;
Arr[3, 0] = 2;
Arr[4, 0] = 2;
Arr[5, 0] = 3;
Arr[6, 0] = 3;
Arr[7, 0] = 3;
Arr[8, 0] = 3;
Arr[9, 0] = 4;
Arr[10, 0] = 4;
Arr[11, 0] = 5;
Arr[12, 0] = 5;
Arr[13, 0] = 5;
Arr[14, 0] = 6;
Arr[15, 0] = 6;
Arr[16, 0] = 7;
Arr[17, 0] = 7;
Arr[18, 0] = 7;
Arr[19, 0] = 7;
Arr[20, 0] = 7;
Arr[21, 0] = 7;
Arr[22, 0] = 8;
Arr[23, 0] = 9;
int IDNum = 1; //查询数字,动态改变值
int login = 0;
int end = Arr.GetLength(0) - 1;
int half = (login + end) / 2;
int searNum = Arr[half, 0];
while (login < end && searNum != IDNum)
{
if (searNum < IDNum)
login = half + 1;
if (searNum > IDNum)
end = half - 1;
half = (login + end) / 2;
searNum = Arr[half, 0];
}
int i = half;
while (searNum == IDNum && i > 0)
{
i--;
login = i + 1;
if (login > end)
login = end;
if (i == 0) //区别位置
login = 0;
searNum = Arr[i, 0];
}
int j = half;
searNum = Arr[j, 0];
while (searNum == IDNum && j < Arr.GetLength(0) - 1)
{
j++;
end = j - 1;
if (login > end)
end = login;
if (j > Arr.GetLength(0) - 1)
end = Arr.GetLength(0) - 1;
searNum = Arr[j, 0];
}
Console.WriteLine(login.ToString());
Console.WriteLine(end.ToString());
Console.ReadLine();