大家好,我正在研究二进制搜索程序。我的算法是正确的,但是当我使用驱动程序运行程序时,我会重新获得值“false”,而不是看起来像这样的表。 Table output(LINK)
这是我的驱动程序和主程序。
public class TestResulter {
public static void main(String[] args) {
//Resulter resulter = new Resulter();
int numberOfItems = 10000;
int item;
int a[ ] = new int[ numberOfItems ];
for( int i = 0; i < 20; i++ )
{
item = Resulter.randomitem( a );
System.out.println( Resulter.binarySearch( a , item ) );
}
}
}
我的主程序是binarySearch算法。
import java.util.Random;
public class Resulter extends TestResulter {
private static class Result {
public Boolean found; // true if found, false if not found
public int index; // index where item was found, -1 if not found
public int steps; // number of comparisons performed
public Result(boolean f, int ind, int st) {
found = f;
index = ind;
steps = st;
}
@Override
public String toString() {
return "Result [found=" + found + ", index=" + index + ", steps=" + steps + "]";
}
}
public static boolean binarySearch(int[] a, int item) {
int start=0, end=a.length-1;
while(end>=start) {
int mid = start + ((end - start) / 2);
if (a[mid] == item)
return true;
if (a[mid] > item)
end = mid-1;
else start = mid+1;
}
return false;
}
public static int randomitem ( int[] a ) {
int i;
Random random = new Random();
int item = random.nextInt( 10999 );
for( i = 0; i < 10000; i++ )
{
a[ i ] = random.nextInt( 10000 );
}
return item;
}
}
我希望我的程序能够从线性搜索程序中获得与我的图像类似的输出。
答案 0 :(得分:2)
以下是您的代码,其中包含一些更改和重构:
public class TestResulter
{
public static void main(String[] args)
{
int numberOfItems = 10000;
int item;
int[] a = new int[numberOfItems];
fillArray(a);
for( int i = 0; i < 20; i++ )
{
item = Resulter.randomitem(a);
System.out.println(Resulter.binarySearch(a, item));
}
}
private static void fillArray(int[] a)
{
Random random = new Random();
for(int i = 0; i < a.length; i++)
a[i] = random.nextInt(10000);
Arrays.sort(a);
}
}
public class Resulter
{
private static class Result
{
public boolean found; // true if found, false if not found
public int index; // index where item was found, -1 if not found
public int steps; // number of comparisons performed
public Result(boolean f, int ind, int st)
{
found = f;
index = ind;
steps = st;
}
@Override
public String toString()
{
return "Result [found=" + found + ", index=" + index + ", steps=" + steps + "]";
}
}
public static Result binarySearch(int[] a, int item)
{
int start=0, end=a.length-1;
int stepCount = 0;
while(end>=start)
{
stepCount++;
int mid = start + ((end - start) / 2);
if(a[mid] == item)
return new Result(true, mid, stepCount);
else if(a[mid] > item)
end = mid-1;
else
start = mid+1;
}
return new Result(false, -1, stepCount);
}
public static int randomitem(int[] a)
{
return new Random().nextInt(10000);
}
}
正如我所看到的,解决方案中的主要问题是:
Arrays.sort(a)
命令。binarySearch
返回了boolean
而不是Result
对象,这是您要打印的对象。答案 1 :(得分:-1)
您的main
函数中存在语法打嗝。将int a[]
更改为int[] a
。
此外,randomitem
中执行的逻辑操作可能是一个促成因素。它item
使用的binarysearch
不是从搜索数组a
中提取的,而是随机生成的。试试return a[random.nestIng(a.length)];
我在移动应用上,所以我的语法可能不完美。