二分查找

前几天我去面试的时候,有一题是关于二分查找的题目;当时我就感觉要悲剧了,因为二分查找我就没写过,只记得个大概的思路而且还要手写代码出来,而且面试都是有时间限制的最后只能空白了。吓的我赶紧写个二分查找教程出来温习下。。。。。好了,废话就说到这吧。
     我们首先来看看能使用二分查询算法的条件:
     1、必须采用顺序结构存储结构;
     2、必须按关键字大小有序排序。
     二分查找的基本思想是将数组中的n个元素分成大致相等的两部分,取数组的a[n/2]与x进行比较,x大于a[n/2]表示x存在于前半部分的数组中,反之表示x存在于后半部分的数组中;重复同样的操作直到找出匹配值x或数组不存在匹配值。
代码如下:

 1 /// <summary>
 2        /// 查找数组中值的索引(二分查找)
 3        /// </summary>
 4        /// <param name="binarysearch">数组</param>
 5        /// <param name="Num">查找值</param>
 6        /// <returns>返回值在数组中的索引(查找值不存在在数据中时返回-1)</returns>
 7        public static int BinarySearch(int[] binarysearch, int Num)
 8        {
 9            int iMin = 0;//最小索引
10            int iMax = binarysearch.Length - 1;//最大索引
11            while (iMin <= iMax)
12            {
13                //取折半的索引
14                int Number = (iMax + iMin) / 2;
15                //判断数组的值是否大于查找值 大于:更改最大索引
16                if (binarysearch[Number] > Num)
17                {
18                    iMax = Number - 1;
19                }
20                //判断数组的值是否小于查找值 小于:更改最小索引
21                else if (binarysearch[(Number)] < Num)
22                {
23                    iMin = Number + 1;
24                }
25                else
26                {
27                    //判断数组的值等于查找值直接返回索引值
28                    return Number;
29                }
30            }
31            return -1;
32        }

 

如有不足或写错的地方欢迎指正,谢谢!!!!

 

posted @ 2018-08-23 11:56  剑弑  阅读(110)  评论(0编辑  收藏  举报