用于二进制搜索的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对象的实例,并将值分配给数组。通过将特定值作为参数传递给搜索来在数组上调用此二进制搜索功能。如果找到,则显示索引,否则,显示相关消息。
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短