第05章 数组 14 练习 12

来源:互联网 发布:网络刺客ii使用教程 编辑:程序博客网 时间:2024/04/30 04:55

鱼欲遇雨:每日都学习一点,持之以恒,天道酬勤!不能用电脑时,提前补上!(2012.8.24)

注:24号在火车上,提前补这一天!要做37个钟头火车,不知道能不能补到卧铺。

 

搜索算法=====二分法搜索算法

代码

 

// TestSearch.javapublic class TestSearch {public static void main(String args[]) {int a[] = { 1, 3, 6, 8, 9, 10, 12, 18, 20, 34};int i = 12;System.out.println(binarySearch(a, i));}public static int binarySearch(int a[], int num) {if(a.length == 0) return -1;int startPos = 0;int endPos = a.length - 1;int m = (startPos + endPos)/2;while(startPos <= endPos) {if(a[m] == num) return m;if(a[m] > num) endPos = m + 1;if(a[m] < num) startPos = m - 1;m = (startPos + endPos)/2;}return -1;}}


 

原创粉丝点击