Java二进制搜索

时间:2015-07-28 17:43:52

标签: java

import javax.swing.JOptionPane;

public class Binary_Search
{

  public static void main(String[] args)
  {

    for (int i = 5000; i < 1000; i++)
    {
        int[] search = new int[1000];
        int guess = Integer.parseInt(JOptionPane.showInputDialog("Please enter a number between 5000 and 5999."));
            while (guess > 5999 || guess < 5000)
            {
            guess = Integer.parseInt(JOptionPane.showInputDialog("Please enter a number between 5000 and 5999."));  
            }

        int comparisons = 0;
        int min = 0;
        int max = search.length - 1;
        int avg = (min + max) / 2; 

        do 
        {
            if (guess > avg)
            {
              int temp = avg;
              avg = (guess + max) / 2;
              min = temp;
              comparisons ++;
            }
            if (guess < avg)
            {
              int temp = avg;
              avg = (guess + min) / 2;
              max = temp;
              comparisons ++;
            }
        } while (guess != avg);
        System.out.println("Your guess was " + guess + " and the number of comparisons was " + comparisons + ".");

    }
  }
}

这是一个我正在处理的简单二进制搜索程序,我知道它可能存在一些问题,但它正在进行中。 我无法弄清楚为什么我的代码在启动时崩溃,谁能告诉我为什么?

1 个答案:

答案 0 :(得分:4)

for (int i = 5000; i < 1000; i++)

你从i = 5000开始 - 然后期望它低于1000?整个循环永远不会执行。