Java 二分查詢(遞迴實現)
阿新 • • 發佈:2019-01-22
廢話不說,直接上程式碼
package com.search; public class SearchOfMid { public static void main(String[] args) { int [] arr = {1,3,4,5,2,5,1,8,9,5}; //常規方式 System.out.println(find(arr,9)); //遞迴實現 System.out.println(recursiveFind(arr,0,arr.length-1,9)); } /* * 二分查詢,返回索引 */ private static int find(int [] arr,int searchKey){ int lowerBound = 0; int upperBound = arr.length -1; int curIn; while(lowerBound <= upperBound){ curIn = (lowerBound + upperBound) / 2; if(arr[curIn] == searchKey){ return curIn; }else{ if(arr[curIn] < searchKey){ lowerBound = curIn + 1; }else{ upperBound = curIn - 1; } } } return -1; } /* * 二分查詢,返回索引,遞迴實現 */ private static int recursiveFind(int[] arr,int start,int end,int searchKey){ if (start <= end) { int middle = (start+end)/2; if (searchKey == arr[middle]) { return middle; } else if (searchKey < arr[middle]) { return recursiveFind(arr, start, middle - 1, searchKey); } else { return recursiveFind(arr, middle + 1, end, searchKey); } } else { return -1; } } }