二分法查找有序数组中的元素
2016-03-31 15:44
435 查看
public class TestSearch { public static void main(String[] args) { int a[] = {1,2,3,4,5,7,9,23,45,68,98,111,333,999}; int i =99; System.out.println(binarySearch(a, i)); } public static int binarySearch(int a[],int num){ if(a.length == 0){ return -1; } int startPos = 0; int lastPos = a.length-1; int m = (startPos+lastPos)/2; while(startPos <= lastPos){ if(num == a[m]){return m;} if(num > a[m]) {startPos = m+1;} if(num < a[m]){lastPos = m-1;} m = (startPos+lastPos)/2; } return -1; } }
相关文章推荐
- Sql Server数据库对象访问权限控制
- C#获取MySql 数据常用的代码
- ZOJ1002
- Android Studio使用总结 [未完待续]
- sqlserver里面的row_number分页问题
- MMDrawerController(0.6.0) 文档翻译(简介,非API文档)
- Codeforces 659G Fence Divercity (组合计数)
- 编译 FFMPEG with nvenc enabled
- scanf()函数用法小结
- (4.6.9)Android属性allowBackup安全风险浅析
- Ubuntu 14.04 LTS Eclipse没有菜单栏解决方案
- Flask、uWSGI and Nginx on Ubuntu 14.04
- 【poj 3292】Semi-prime H-numbers
- DLETE 和 TRUNCATE的区别
- Android开源项目分类汇总(六)工具库
- 网络数据传输的封装
- 网易游戏面试经验(三)
- 360技术笔试编程题
- 牛人集合
- leetcode 121. Best Time to Buy and Sell Stock