BinarySearch
binary search or half-interval search algorithm finds the position of a specified value (the input "key") within a sorted array. In each step, the algorithm compares the input key value with the key value of the middle element of the array. If the keys match, then a matching element has been found so its index, or position, is returned. Otherwise, if the sought key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right. If the remaining array to be searched is reduced to zero, then the key cannot be found in the array and a special "Not found" indication is returned.
A binary search halves the number of items to check with each iteration, so locating an item (or determining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.
View Code
1 /* 2 * O(logn) 3 * 4 */ 5 public class BinarySearch { 6 7 public static void main(String[] args) { 8 // TODO Auto-generated method stub 9 int[] a=new int[]{1,2,3,4,5,7,8,9}; 10 int target=5; 11 System.out.println(binarySearch(a, target, 0, a.length-1)); 12 target=6; 13 System.out.println(binarySearch(a, target, 0, a.length-1)); 14 } 15 /** 16 * 17 * @param input:the sorted input array 18 * @param target:the searching number 19 * @param from:the start of the array 20 * @param to:the end of the array 21 * @return 22 */ 23 24 public static String binarySearch(int[] input,int target,int from,int to){ 25 int range=to-from; 26 if(range>0){ 27 int mid = (from+to)/2; 28 if(input[mid]==target){ 29 return String.valueOf(mid); 30 } 31 else if(input[mid]>target){ 32 return binarySearch(input,target,from,mid-1); 33 } 34 else{ 35 return binarySearch(input, target, mid+1, to); 36 } 37 } 38 else{ 39 if(input[from]==target){ 40 return String.valueOf(from); 41 } 42 else{ 43 return "null"; 44 } 45 } 46 } 47 48 }

浙公网安备 33010602011771号