折半查找
来源:互联网 发布:单片机驱动5v继电器 编辑:程序博客网 时间:2024/05/29 12:35
public class Test {public static void main(String[] args) {int[] intArr = { 1, 1, 1, 7, 7, 10, 11, 12, 13, 14, 54, 54, 66, 90,267, 345, 456, 789, 45654 };System.out.println(binarySearch(intArr, 0, intArr.length - 1, 14));}public static boolean binarySearch(int[] arr, int start, int end, int target) {if (start >= arr.length || end < 0<span style="font-family: Arial, Helvetica, sans-serif;">)</span>return false;int index = (start + end) / 2;if (arr[index] < target) { // 右边return binarySearch(arr, index + 1, end, target);} else if (arr[index] > target) { // 左边return binarySearch(arr, 0, index - 1, target);} else {return true;}}}
总结:(1)折半查找需要数据已经排好了序了。
(2)在写过程中,遇到了栈溢出,原因很简单,递归的时候,条件写的不好。就很容易循环了,所以写递归的时候需要非常的仔细,判断跳出递归的条件
是否全都考虑到了。
(3)折半查找还可以使用非递归的方式。
0 0
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- @QueryParam和@PathParam比较 (2011-12-11 22:39:15)
- 2、spss做均值比较分析
- 分页查询超时问题(1)
- struct对齐问题
- 常用SQL查询语句
- 折半查找
- ping的原理
- 常见的重写view
- java this关键字
- ANDROID基础学习笔记_4.1_采用pull解析xml文件
- PAT00-自测4. Have Fun with Numbers (20)
- WINDOWS的错误代码对应的故障
- 2015年创业中遇到的技术问题:81-90
- nova vnc proxy基本原理