程序代码:
class Program
{
private static string[] arrIndex;
private static int[] arrMain;
static void Main(string[] args)
{
//初始化数据
initTable();
Console.WriteLine("请输入要查找的值:");
string value = Console.ReadLine();
int v = int.Parse(value);
//根据要查找的值,查出索引
string str = findIndex(v);
int star = 0;
int end = 0;
if (str.IndexOf(",") > 0)
{
string[] arrStr = Regex.Split(str, ",");
star = int.Parse(arrStr[0]);
end = int.Parse(arrStr[1]);
}
else
{
star = int.Parse(str);
end = arrMain.Length - 1;
}
bool flag = false;
//根据索引,在主表中查找数据
for (int i = star; i <= end; i++)
{
if (arrMain[i] == v)
{
Console.WriteLine("已找到查询的值,对应主表下标[" + i + "]");
flag = true;
break;
}
}
if (!flag)
{
Console.WriteLine("未在主表中找到要查询的值");
}
Console.ReadKey();
}
/// <summary>
/// 初始化数据
/// </summary>
public static void initTable()
{
initIndexTable();
initMainTable();
}
/// <summary>
/// 初始化索引表
/// </summary>
public static void initIndexTable()
{
arrIndex = new string[] { "14,0", "34,5", "66,10", "85,14" };
}
/// <summary>
/// 初始化主表
/// </summary>
public static void initMainTable()
{
arrMain = new int[19] { 8, 14, 6, 9, 10, 22, 34, 18, 19, 31, 40, 38, 54, 66, 71, 78, 68, 80, 85 };
}
/// <summary>
/// 查找值所对应的索引
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string findIndex(int value)
{
string str = "";
for (int i = 0; i < arrIndex.Length - 1; i++)
{
string[] arrTemp = Regex.Split(arrIndex[i], ",");
string[] arrTemp1 = Regex.Split(arrIndex[i + 1], ",");
if (value <= int.Parse(arrTemp[0]))
{
str = arrTemp[1] + "," + arrTemp1[1];
break;
}
else if (value > int.Parse(arrTemp[0]) && value <= int.Parse(arrTemp1[0]))
{
if (i < arrIndex.Length - 2)
{
string[] arrTemp2 = Regex.Split(arrIndex[i + 2], ",");
str = arrTemp1[1] + "," + arrTemp2[1];
break;
}
else
{
str = arrTemp1[1];
break;
}
}
}
if (str == "")
{
string[] arrTemp = Regex.Split(arrIndex[arrIndex.Length - 1], ",");
str = arrTemp[1];
}
return str;
}
}