有序数组的二分查找
来源:互联网 发布:窗帘淘宝生意进货 编辑:程序博客网 时间: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
- 有序数组的二分查找
- 有序数组的二分查找
- 有序数组的二分查找
- 有序数组\二分查找
- 有序数组二分查找
- 有序 循环数组的二分查找
- 旋转有序数组的二分查找
- 有序数组的二分查找程序
- 9.5-字符串有序数组的二分查找
- 对于有序数组的二分查找算法
- 旋转有序数组的二分查找
- 基于有序数组的二分查找
- 旋转有序数组的二分查找
- 二分数组的扩展:二分查找循环有序数组
- 有序数组中的二分查找
- 有序数组之二分查找
- 二分查找(有序数组中查找需要的数)
- 循环有序数组/旋转数组的二分查找
- BlockingQueue
- servlet使用声明式异常处理指定错误跳转页面,ie下无法正常显示
- unit11 practice
- CursorAdapter中getView newView bindView异同
- 用Parallel.For()和Parallel.For<TLocal>()方法实现并行运行迭代
- 有序数组的二分查找
- 用div画横线
- C# Parallel用法
- 关于android中PendingIntent.getBroadcase的注册广播
- Android 中的 Service 全面总结
- 时间复杂度
- Activity及Intent
- android service被系统回收的解决方法
- Activity的四种launchMode