二分查找的递归和非递归实现
Posted yinhuanxu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找的递归和非递归实现相关的知识,希望对你有一定的参考价值。
public class BinarySearch
//非递归
public static int binSearch1(int[] arr, int target)
if(arr == null || arr.length == 0)
return -1;
int left = 0, right = arr.length - 1;
while(left <= right)
int mid = (left + right) / 2;
if(arr[mid] == target)
return mid;
if(arr[mid] < target)
left = mid + 1;
if(arr[mid] > target)
right = mid - 1;
return -1;
//递归
public static int binSearch2(int[] arr, int target, int left, int right)
if(arr == null || arr.length == 0)
return -1;
if(left > right)
return -1;
int mid = (left + right) / 2;
if(arr[mid] == target)
return mid;
if(arr[mid] > target)
return binSearch2(arr, target, left, mid-1);
if(arr[mid] < target)
return binSearch2(arr, target, mid+1, right);
return -1;
public static void main(String[] args)
int[] testArr = new int[]1,2,3,5,8,9,12,13,15,20;
System.out.println(binSearch1(testArr, 3));
System.out.println(binSearch2(testArr, 3, 0, 10));
以上是关于二分查找的递归和非递归实现的主要内容,如果未能解决你的问题,请参考以下文章