[英]how to binary search one specific element in an array?
i have a binary search algorithm set up but i didn't know how to make it work like what where im suppose to tell it to look for an element and show if it is found or not any tip would help thank you我设置了一个二分搜索算法,但我不知道如何让它像我想告诉它寻找一个元素并显示它是否找到的那样工作,任何提示都会有所帮助,谢谢
public static int search(int arr[], int x)
{
int startIndex = 0 ;
int endIndex = arr.length-1;
while ( startIndex <=endIndex){
int midpoint = (startIndex + endIndex )/2;
if(arr[midpoint]==x)
return midpoint;
else if(arr[midpoint]<x)
startIndex=midpoint+1;
else
endIndex = midpoint = -1;
}
return -1;
}
//here i want to make it search for 6
public static void main (String [] args ){
search v = new search();
int [] test = {1,99,6,32,4,6,33,90};
for (int element: test) {
System.out.println("the elements of array: "+ element);
int x = 6;
int result=v.binarySearch();
}
Binary Search works as, Search a sorted array by repeatedly dividing the search interval in half.二分搜索的工作原理是,通过重复将搜索间隔分成两半来搜索排序数组。 Begin with an interval covering the whole array.
从覆盖整个数组的间隔开始。 If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.
如果搜索键的值小于区间中间的项,则将区间缩小到下半部分。 Otherwise, narrow it to the upper half.
否则,将其缩小到上半部分。 Repeatedly check until the value is found or the interval is empty.
反复检查,直到找到值或区间为空。
int[] test = {1, 99, 6, 32, 4, 6, 33, 90};
int num = 6;
Arrays.sort(test);
System.out.println(binarySearch(test, num, 0, test.length));
logic for the binary search is given below as,二进制搜索的逻辑如下所示,
public int binarySearch(int arr[], int num, int min, int max) {
if (min > max) {
return -1;
}
int mid = min + (max - min) / 2;
if (arr[mid] == num) {
return mid;
} else if (arr[mid] < num) {
return binarySearch(arr, num, mid + 1, max);
}
return binarySearch(arr, num, min, mid - 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.