赞
踩
怕记不住,
对于一个有序数据,可以使用二分查找,前提是数组必须有序,时间复杂度为O(logn)。
二分查找通常有两种写法:递归、非递归
(1)二分查找递归
/** * 二分查找 */ public static int binarySerch(int[] array, int value, int left, int right) { if(left > right) { return -1; } int middle = (left + right) >>> 1; if(array[middle] == value) { return middle; }else if(array[middle] > value) { return binarySerch(array, value, left, middle-1); }else { return binarySerch(array, value, middle+1, right); } }
(2)二分查找非递归
/** * 二分查找 * @author lijialin * */ public class Main { public static int binarySearch(int[] array, int k) { int left = 0; int right = array.length-1; while(left <= right) { int mid = (left + right) >> 1; if(array[mid] == k) return mid; else if(array[mid] < k) { left = mid + 1; }else { right = mid - 1; } } return -1; } public static void main(String[] args) { // test case int[] array = {1,2,3,4,5,6,7,8,9}; for(int i = 0; i < array.length; i++) { System.out.println(binarySearch(array, array[i])); } } }
(3)Collections.binarySearch();
在实际工作中,无需我们自己动手实现二分查找,Collections为我们提供了二分查找方法。
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
Collections.sort(list);
int index = Collections.binarySearch(list, 4);
System.out.println(index);
Collections.binartSearch的源码使用了非递归的方式进行二分查找,对于可以随机访问的存储结构(如数组)、与链式存储结构(如链表)分别进行了实现:
private static <T> int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) { int low = 0; int high = list.size()-1; while (low <= high) { int mid = (low + high) >>> 1; Comparable<? super T> midVal = list.get(mid); int cmp = midVal.compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } private static <T> int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key) { int low = 0; int high = list.size()-1; ListIterator<? extends Comparable<? super T>> i = list.listIterator(); while (low <= high) { int mid = (low + high) >>> 1; Comparable<? super T> midVal = get(i, mid); int cmp = midVal.compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found }
注:学渣心里苦,不要学楼主,平时不努力,考试二百五,哭 ~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。