有序数组的二分查找

来源:互联网 发布:窗帘淘宝生意进货 编辑:程序博客网 时间:2024/04/27 06:37

有序数组二分查找的基本原理:因为数组是有序的,先找到中间位置的值,如果目标比这个值大,那么该目标必定在数组的右半部分,以此循环或者递归,一直找到这个数值为止。此算法的时间复杂度为O(logN),N为数组的长度 (2的X次方 == N,所以复杂度即为 O(logn) )

 

public class SortedArrayBinarySearch {        public static void main(String[] args) {        int[] source=new int[]{1,3,5,7,9,12};         int key = 12;        System.out.println(binaryRecurSearch(source, key));;        System.out.println(binarySearchLoop(source, key));;    }        public static int binaryRecurSearch(int[] source, int key){        return binarySearchRecursive(source, key,0,source.length-1);    }        private static int binarySearchRecursive(int[] source, int key,int beginIndex,int endIndex){        int midIndex = (beginIndex+endIndex)/2;        if(key<source[beginIndex]  ||  key>source[endIndex] || beginIndex>endIndex){              return -1;          }          System.out.println("=======");        if(key == source[midIndex]){            return midIndex;        }else if(key > source[midIndex]){            return binarySearchRecursive(source, key, midIndex+1, endIndex);        }else{            return binarySearchRecursive(source, key, beginIndex, midIndex-1);        }            }        public static int binarySearchLoop(int[] source, int key){        int beginIndex = 0;        int endIndex = source.length-1;                        while(true){            System.out.println("=======");            if(key<source[beginIndex] || key>source[endIndex] ||  beginIndex>endIndex){                  return -1;              }              int midIndex = (beginIndex+endIndex)/2;            if(key == source[midIndex]){                return midIndex;            }else if(key > source[midIndex]){                beginIndex = midIndex +1;            }else{                endIndex = midIndex -1;            }        }            }}

 

0 0
原创粉丝点击