publicclassBinarySearch{privateBinarySearch(){}publicstaticintbinarySearch(Comparable[] arr,int n, Comparable target){int l =0, r = n -1;// 在[l...r]的范围里寻找targetwhile(l <= r){// 当 l == r时,区间[l...r]依然是有效的int mid = l +(r - l)/2;if(arr[mid].compareTo(target)==0)return mid;if(target.compareTo(arr[mid])>0)
l = mid +1;// target在[mid+1...r]中; [l...mid]一定没有targetelse// target < arr[mid]
r = mid -1;// target在[l...mid-1]中; [mid...r]一定没有target}return-1;}publicstaticvoidmain(String[] args){int n =(int)Math.pow(10,7);
Integer data[]= Util.generateOrderedArray(n);long startTime = System.currentTimeMillis();for(int i =0; i < n ; i ++)if(i !=binarySearch(data, n, i))thrownewIllegalStateException("find i failed!");long endTime = System.currentTimeMillis();
System.out.println("Binary Search test complete.");
System.out.println("Time cost: "+(endTime - startTime)+" ms");}}
publicclassUtil{privateUtil(){}publicstatic Integer[]generateRandomArray(int n,int rangeL,int rangeR){assert n >0&& rangeL <= rangeR;
Integer[] arr =newInteger[n];for(int i =0; i < n; i++)
arr[i]=(int)(Math.random()*(rangeR - rangeL +1))+ rangeL;return arr;}publicstatic Integer[]generateOrderedArray(int n){assert n >0;
Integer[] arr =newInteger[n];for(int i =0; i < n; i++)
arr[i]= i;return arr;}}
3-2 改变变量定义,依然可以写出正确的算法
如何写出正确的程序(总结)
明确变量的含义
循环不变量
小数据量调试
大数据量测试
publicclassBinarySearch{privateBinarySearch(){}publicstaticintbinarySearch(Comparable[] arr,int n, Comparable target){int l =0, r = n;// 在[l...r)的范围里寻找targetwhile(l < r){// 当 l == r 时, 区间[l...r)是一个无效区间int mid = l +(r - l)/2;if(arr[mid].compareTo(target)==0)return mid;if(target.compareTo(arr[mid])>0)
l = mid +1;// target在[mid+1...r)中; [l...mid]一定没有targetelse// target < arr[mid]
r = mid;// target在[l...mid)中; [mid...r)一定没有target}return-1;}publicstaticvoidmain(String[] args){int n =(int)Math.pow(10,7);
Integer data[]= Util.generateOrderedArray(n);long startTime = System.currentTimeMillis();for(int i =0; i < n ; i ++)if(i !=binarySearch(data, n, i))thrownewIllegalStateException("find i failed!");long endTime = System.currentTimeMillis();
System.out.println("Binary Search 2 test complete.");
System.out.println("Time cost: "+(endTime - startTime)+" ms");}}
publicclassUtil{privateUtil(){}publicstatic Integer[]generateRandomArray(int n,int rangeL,int rangeR){assert n >0&& rangeL <= rangeR;
Integer[] arr =newInteger[n];for(int i =0; i < n; i++)
arr[i]=(int)(Math.random()*(rangeR - rangeL +1))+ rangeL;return arr;}publicstatic Integer[]generateOrderedArray(int n){assert n >0;
Integer[] arr =newInteger[n];for(int i =0; i < n; i++)
arr[i]= i;return arr;}}