用于二进制搜索的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对象的实例,并将值分配给数组。通过将特定值作为参数传递给搜索来在数组上调用此二进制搜索功能。如果找到,则显示索引,否则,显示相关消息。
以上是 用于二进制搜索的Java程序(递归) 的全部内容, 来源链接: utcz.com/z/341091.html