java搜索算法——二分法查找
搜索建立在排好序的基础之上
TestSearch.java
//搜索算法 public class TestSearch { public static void main(String[] args) { //搜索建立在排好序的基础之上 int a[] = { 1, 3, 6, 8, 9, 10, 12, 18, 20, 34 }; //12这个值位于a[]的第几个位置 int i = 12; System.out.println(search(a, i)); System.out.println(binarySearch(a, i));//返回值12在数组里面的位置(下标) } //搜索全部 public static int search(int[] a, int num) { for(int i=0; i<a.length; i++) { if(a[i] == num) return i; } return -1; } //二分法查找 /* int[] a 查找的数组 int num 查找数组中的值 return 返回值的位置 */ 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(num == a[m]) return m;//找到了返回m if(num > a[m]) { startPos = m + 1;//起始位置向右调整 } if(num < a[m]) { endPos = m -1;//结束位置向左调整 } m = (startPos + endPos) / 2;//重新计算中间的位置 } return -1;//没有找到返回-1 } }
F:\java>javac TestSearch.java F:\java>java TestSearch 6 6 F:\java>