赞
踩
- public static void main(String[] args) {
- Integer[] arr = new Integer[]{12,15,20,36,45,66,72,81,90};
- int des = 22;
- int search = binarySearch(arr, des);
- System.out.println(search);
- int recursive = binarySearchRecursive(arr, 0 , arr.length-1 ,des);
- System.out.println(recursive);
- }
-
- /**
- * 二分查找 非递归 如果数组中不存在要查询的数返回-1
- *
- * @param arr
- * @param des
- * @return
- */
- public static int binarySearch(Integer[] arr, int des){
- int start = 0;
- int end = arr.length-1;
-
- while (start <= end) {
- int middle = (( end - start )>>1)+ start;
- if (des == arr[middle]) {
- return middle+1;
- }else if (des < arr[middle]) {
- end = middle-1;
- }else if (des > arr[middle]) {
- start = middle+1;
- }
- }
- return -1;
- }
-
- /**
- * 二分查找 递归方式 如果数组中不存在要查询的数返回-1
- *
- * @param args
- * @param des
- * @return
- */
- public static int binarySearchRecursive(Integer[] args ,int start, int end, int des){
- int middle = -1;
- if (start <= end) {
- middle = (start + end) >> 1;
- if (des == args[middle]) {
- return middle+1;
- }else if (des < args[middle]) {
- end = middle -1;
- return binarySearchRecursive(args, start, end, des);
- }else if (des > args[middle]) {
- start = middle +1;
- return binarySearchRecursive(args, start, end, des);
- }
- }
- return middle;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。