【发布时间】:2015-10-12 21:22:08
【问题描述】:
我正在开发一个程序,它会要求用户输入一个介于 3000-3100 之间的值,然后进行二分搜索并显示它进行了多少次比较。总体而言,程序的搜索部分运行良好;然而,我的教授希望我打印出做数学的程序。例如,我需要程序显示计算机进行二进制搜索数学,并显示程序查找输入数字所需的比较。
我有一个comparisonCount,当我进行比较时我会增加它,但结果不是我认为的那样。比如我的教授说如果你输入3067应该有7个比较,但目前程序是4,计数器是3。
您能帮我找出差异的原因吗?
代码如下:
package binary.search;
import java.util.Scanner;
public class BinarySearch
{
public static void binarySearch(int[] array, int lowerbound, int upperbound, int key)
{
int position;
int comparisonCount = 1; // counting the number of comparisons
// To start, find the subscript of the middle position.
position = (lowerbound + upperbound) / 2;
//System.out.println();
while ((array[position] != key) && (lowerbound <= upperbound))
{
comparisonCount++;
if (array[position] > key) // If the number is > key, ..
{
upperbound = position - 1; // decrease position by one.
}
else
{
lowerbound = position + 1; // Else, increase position by one.
}
position = (lowerbound + upperbound) / 2;
}
if (lowerbound <= upperbound)
{
System.out.println("The number " + key + " was found in array.");
System.out.println("The binary search found the number after " + comparisonCount + " comparisons.");
}
else
System.out.println("That number is not in this array. The binary search completed "
+ comparisonCount + " comparisons.");
}
public static void main(String[] args)
{
// Set up variables
int arrLength = 100;
Scanner inp = new Scanner(System.in);
int[] num = new int[arrLength]; //Create array
int repeat = 1; //Boolean for repeat loop
char yesNo;
int upperLim = 3100;
int lowerLim = 3000;
//Populate array
while (repeat == 1)
{
int value = 0;
int valid = 0;
for (int i = 0; i < num.length; i++)
{
num[i] = i + lowerLim;
}
//Get integer from user
do
{
System.out.print("Please enter a number between " + lowerLim + " and " + upperLim + ": ");
value = inp.nextInt();
if (value < lowerLim || value > upperLim)
{
System.out.print("That wasn't a valid number. Please try again. \n");
}
}
while (value < lowerLim || value > upperLim);
//Run binary search
binarySearch(num, 0, arrLength - 1, value);
do
{
valid = 0;
System.out.print("Would you like to rerun the program? Y for yes, N for no.\n");
yesNo = (inp.next()).charAt(0);
if (yesNo == 'Y')
{
repeat = 1;
valid = 1;
}
else if (yesNo == 'N')
{
repeat = 0;
valid = 1;
}
else
System.out.print("Not a valid response. \n");
}
while (valid != 1);
}
}
}
【问题讨论】:
-
为什么不添加一个计数器,并在有比较时增加它?
-
我该怎么做呢?声明一个计数器,然后使用 counter++ ????就像我需要它打印它确实 (3100 -3000)/2 = 50,所以 3047 将位于比例的下半部分,依此类推,直到找到数字。柜台会这样做吗?
-
是的。整数计数器=0;然后当你需要增加它时,调用 counter++
-
由于某种原因,计数器仍然没有给我正确的读数。我的教授说如果你输入3067应该是7比较,目前程序说4,计数器说3......
-
@JosephReed for 3067 比较的数字将是 3049,3074,3061,3067。所以不能有 7 个比较。
标签: java search while-loop binary