折半算法,也就是二分查找法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了折半算法,也就是二分查找法相关的知识,希望对你有一定的参考价值。
一:用递归算法
/// <summary> /// /// </summary> /// <param name="num">数组</param> /// <param name="curr">被查找的数</param> /// <param name="count">需要查找的索引位置</param> /// <param name="isAfter">true 向前,false 向后</param> /// <returns></returns> public static int change(int[] num, int curr, int count, bool isAfter) { int index = count; if (isAfter) index = Convert.ToInt32(Math.Ceiling(count / 2d)); //判断索引是否越界 if (index >= num.Length) { return -1; } if (num[index] < curr) //后半部分查找 { return change(num, curr, index + num.Length, true); } else if (num[index] > curr) //前半部分查找 { return change(num, curr, index - 1, false); } else if (curr == num[index]) { return index; } return -1; }
二:用while循环查找
/// <summary> /// /// </summary> /// <param name="num">需要查找的数组</param> /// <param name="curr">查找的数</param> /// <returns></returns> public static int change2(int[] num, int curr) { int count = num.Length; int index = Convert.ToInt32(Math.Ceiling(count / 2d)); while (true) { //判断索引是否越界 if (index >= num.Length) { return -1; } if (num[index] < curr) { count = index + num.Length; index = Convert.ToInt32(Math.Ceiling(count / 2d)); continue; } else if (num[index] > curr) { count = index - 1; index = count; continue; } else if (curr == num[index]) { return index; } } }
测试:
int[] num = { 1, 2, 8, 9, 95, 98, 100, 190, 900 };
int results = change(num, 100, num.Length, false);
int resultss = change2(num, 100);
以上是关于折半算法,也就是二分查找法的主要内容,如果未能解决你的问题,请参考以下文章