折半算法的C#实现方式-递归和非递归
2015-04-19 15:22 咒语 阅读(506) 评论(0) 编辑 收藏 举报这个算法,相信大家都懂,但是不真正的手动写一遍,总觉得不得劲。这不,手动写一遍就是有不一样的效果出现了。
往左折半,还是往右走比较简单,其实这两个算法最关键的是:退出条件 min > max 和下次折半时下标或上标位置要+1或-1
/// <summary> /// 递归的纯算法实现 /// </summary> /// <param name="arrList"></param> /// <param name="min"></param> /// <param name="max"></param> /// <param name="des"></param> /// <returns>命中目标的索引</returns> public int RecursionSearch(int[] arrList, int min, int max, int des) { if (min > max) return -1; var midIndex = (min + max) / 2; var midValue = arrList[midIndex]; if (midValue == des) return midIndex; return midValue < des ? RecursionSearch(arrList, midIndex + 1, max, des) : RecursionSearch(arrList, min, midIndex - 1, des); } /// <summary> /// 普通算法纯算法实现 /// </summary> /// <param name="arrList"></param> /// <param name="des"></param> /// <returns></returns> public int CommonSearch(int[] arrList, int des) { var min = 0; var max = arrList.Length - 1; while (min < max) { var mid = (max + min) / 2; var midValue = arrList[mid]; if (midValue == des) return mid; if (midValue < des) min = mid + 1; //向右搜索 if (midValue > des) max = mid - 1; //向左搜索 } return -1; }