用于二进制搜索的Java程序(递归)
以下是Java中递归二进制搜索的程序-
示例
public class Demo{
int rec_bin_search(int my_arr[], int left, int right, int x){
if (right >= left){
int mid = left + (right - left) / 2;
if (my_arr[mid] == x)
return mid;
if (my_arr[mid] > x)
return rec_bin_search(my_arr, left, mid - 1, x);
return rec_bin_search(my_arr, mid + 1, right, x);
}
return -1;
}
public static void main(String args[]){
Demo my_object = new Demo();
int my_arr[] = { 56, 78, 90, 32, 45, 99, 104};
int len = my_arr.length;
int x = 104;
int result = my_object.rec_bin_search(my_arr, 0, len - 1, x);
if (result == -1)
System.out.println("The element is not present in the array");
else
System.out.println("The element has been found at index " + result);
}
}输出结果
The element has been found at index 6
名为Demo的类包含二进制搜索功能,该功能采用左向右键和需要搜索的值。一旦执行了二进制搜索,主函数就会创建Demo对象的实例,并将值分配给数组。通过将特定值作为参数传递给搜索来在数组上调用此二进制搜索功能。如果找到,则显示索引,否则,显示相关消息。
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短