【问题标题】:How to print the math a computer does for binary search如何打印计算机为二进制搜索所做的数学运算
【发布时间】: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


【解决方案1】:

七次迭代是在一百个集合中找到一个数字所需的最大值。这是因为log<sub>2</sub>100 介于 6 到 7 之间,您需要使用这两个值中较高的值才能确定找到它。

但是,由于其工作方式的原因,某些特定值可能会更少。让我们更改您的代码,以便它输出它在每个阶段所做的事情(只是添加了一些输出,标有//&lt;&lt;here//&lt;&lt; 的部分):

while ((array[position] != key) && (lowerbound <= upperbound)) {
    System.out.print(String.format(                        //<<here
        "Step %d, lo=%2d, hi=%2d, mid=%2d, [mid]=%4d, ", 
        comparisonCount, lowerbound, upperbound,
        position, array[position]));                       //<<
    comparisonCount++;
    if (array[position] > key) {
        upperbound = position - 1;
        System.out.println(String.format(                  //<<here
            "too high, hi:=%2d", upperbound));             //<<
    } else {
        lowerbound = position + 1;
        System.out.println(String.format(                  //<<here
            "too low,  lo:=%2d", lowerbound));             //<<
    }
    position = (lowerbound + upperbound) / 2;
}
if (lowerbound <= upperbound) {
    System.out.println(String.format(                      //<<here
        "Step %d, lo=%2d, hi=%2d, mid=%2d, [mid]=%4d, found!", 
        comparisonCount, lowerbound, upperbound,
        position, array[position]));                       //<<
    System.out.println("The number " + key +
        " was found in array.");
    System.out.println("The binary search found the number after "
        + comparisonCount + " comparisons.");
}

例如,如果您搜索3049,您基本上会立即找到:

Step 1: lo= 0, hi=99, mid=49, [mid]=3049, found!

对于3067 的具体值,如下所示:

Step 1: lo= 0, hi=99, mid=49, [mid]=3049, too low,  lo:=50
Step 2: lo=50, hi=99, mid=74, [mid]=3074, too high, hi:=73
Step 3: lo=50, hi=73, mid=61, [mid]=3061, too low,  lo:=62
Step 4: lo=62, hi=73, mid=67, [mid]=3067, found!

如您所见,因此进行了四次迭代。如果你想看完整的七次迭代,你可以搜索3099

Step 1, lo= 0, hi=99, mid=49, [mid]=3049, too low,  lo:=50
Step 2, lo=50, hi=99, mid=74, [mid]=3074, too low,  lo:=75
Step 3, lo=75, hi=99, mid=87, [mid]=3087, too low,  lo:=88
Step 4, lo=88, hi=99, mid=93, [mid]=3093, too low,  lo:=94
Step 5, lo=94, hi=99, mid=96, [mid]=3096, too low,  lo:=97
Step 6, lo=97, hi=99, mid=98, [mid]=3098, too low,  lo:=99
Step 7, lo=99, hi=99, mid=99, [mid]=3099, found!

【讨论】:

    猜你喜欢
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 2016-10-18
    相关资源
    最近更新 更多