Java实现二分查找递归和非递归
程序员文章站
2022-03-14 20:41:09
...
Java实现二分查找递归和非递归
public class Demo {
public static void main(String[] args) {
int[] arr={-1,0,3,5,9,12};//查找的数组
int searchNum=13;//查找的目标数
Arrays.sort(arr);
int resultOne=binarySearchOne(arr,searchNum,0,arr.length-1);
System.out.println(resultOne);
int resultTwo=binarySearchTwo(arr,searchNum);
System.out.println(resultTwo);
}
/**
* 递归实现
* @param arr
* @param searchNum
* @param start
* @param end
* @return
*/
public static int binarySearchOne(int[] arr,int searchNum,int start,int end){
if(start>end)
return -1;
int middle=(start+end)/2;
if(searchNum<arr[middle])
return binarySearchOne(arr,searchNum,start,middle-1);
else if(searchNum>arr[middle])
return binarySearchOne(arr,searchNum,middle+1,end);
else
return middle;
}
/**
* 非递归实现
* @param arr
* @param searchNum
* @return
*/
private static int binarySearchTwo(int[] arr, int searchNum) {
int start=0;
int end=arr.length-1;
while(start<=end){
int middle=(start+end)/2;
if(searchNum<arr[middle])
end=middle-1;
else if(searchNum>arr[middle])
start=middle+1;
else
return middle;
}
return -1;
}
}
上一篇: php字符替换的实现方法
下一篇: linux修改进程所有者的问题
推荐阅读