截半查找,跟顺序查找相似,但其效率更高,特别是数量越多的情况下,其基本形式为:
查找:
int[] a = new int[8] { 4, 13, 22, 34, 41, 52, 64, 70 };
输入要找的数:
int find = Convert.ToInt32(Console.ReadLine());设定下标:
int kaiShi = 0, jieShu = a.Length - 1, zhongJian; for (int i=0;i<7 ;i++ ) {截半查找:
zhongJian = (kaiShi + jieShu) / 2; if (a[zhongJian] == find) { Console.WriteLine("找到啦!是第{0}个数", a[i]); break; }如果没找到,在需要的一半数组中查找,每次排除一半,直到全部找完:
else { if (a[zhongJian] < find) { kaiShi = zhongJian + 1; } else { jieShu = zhongJian - 1; } if (kaiShi > jieShu) {最后输出:
Console.WriteLine("没找到"); break; } } }