在Java中,编写一个递归版本的二分搜索算法需要遵循以下步骤:
以下是一个递归版本的二分搜索算法的Java实现:
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 11, 13};
int target = 7;
int result = binarySearch(arr, target, 0, arr.length - 1);
System.out.println("Target found at index: " + result);
}
public static int binarySearch(int[] arr, int target, int start, int end) {
if (start > end) {
return -1; // Target not found
}
int mid = start + (end - start) / 2;
if (arr[mid] == target) {
return mid; // Target found
} else if (target < arr[mid]) {
return binarySearch(arr, target, start, mid - 1); // Search in the left half
} else {
return binarySearch(arr, target, mid + 1, end); // Search in the right half
}
}
}
这个实现中,binarySearch方法是一个递归方法,它接受一个整数数组arr、目标值target以及搜索范围的起始索引start和结束索引end。如果找到目标值,该方法将返回其在数组中的索引;否则,返回-1。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。