【发布时间】:2022-01-22 07:29:55
【问题描述】:
我设置了二进制搜索算法,但我不知道如何使它工作 就像我想告诉它寻找一个元素并显示它是否找到的地方 任何提示都会有所帮助 谢谢
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();
}
【问题讨论】:
-
二分查找要求首先对元素进行排序。
-
你还有一些非常好的语法错误。您的方法是静态的并称为
search,但您在对象v上调用它并调用binarySearch。这些都没有任何意义。