查找算法复习(1)--二分查找法

二分查找法要求被查找的线性表已经排序。

每一次查找,按中间索引把表分为左右两部分,通过对比中间值与目标值的大小,决定下一次查找在左表还是右表,直到无法再分割。

 1         public static int BinarySearch(string[] datalist, string key)
 2         {
 3             int low = 0;
 4             int high = datalist.Length - 1;//两个下标,决定查找的区间
 5             int middle;
 6             while (low <= high)//无法再分割就结束
 7             {
 8                 middle = (low + high) / 2;//中间下标
 9                 if (datalist[middle].CompareTo(key) > 0)//与中间值比较,缩小查找区间
10                     high = middle - 1;
11                 else if (datalist[middle].CompareTo(key) < 0)
12                     low = middle + 1;
13                 else
14                     return middle;
15             }
16             return -1;
17         }

使用

 1             string[] a = new string[] { "khlin", "hzluo", "jjguo", "hhchen", "jxhan", "lxiao", "jsxiao", "wwang", "lsxie", "lwang" };
 2            
 3             SelectedSort(a);
 4             foreach(string stra in a)
 5                 Console.Write("{0}, ",stra);
 6             Console.WriteLine();
 7             string target1 = "jjguo";
 8             Console.WriteLine("{0} index: {1}", target1, BinarySearch(a, target1));
 9             string target2 = "lsxie";
10             Console.WriteLine("{0} index: {1}", target2, BinarySearch(a, target2));
11             string target3 = "hello";
12             Console.WriteLine("{0} index: {1}", target3, BinarySearch(a, target3));    

posted @ 2014-04-23 15:14  kingsleylam  阅读(321)  评论(0编辑  收藏  举报