【问题标题】:Binary search with file reading goes infinite loop带有文件读取的二进制搜索进入无限循环
【发布时间】:2018-06-17 18:49:13
【问题描述】:

我想实现二进制搜索,但搜索键是外部提供的。这意味着我的硬盘中有一个文件。我想从此文件中读取键值。为此我写了一段代码。但是代码进入了无限循环。

这是我的代码:

public class T5 {
public static void main(String args[])throws Exception{
    double arr[]= new double[]{86.0,12.0,55.0,90.0,77.0,22.0,25.0,33.0,45.0,20.0,23.0};
    int first=0;
    int last=(arr.length)-1;
    Scanner x= new Scanner(new File("D:\\Test_1.txt"));
    while(x.hasNext()){
        double a =x.nextDouble();
        while(first<=last){
            int mid=(first+last)/2;
            if(arr[mid]==a){
                System.out.println("Search successful");
            }
            if(arr[mid]<a){
                last=mid+1;
            }
            else{
                last=mid-1;
            }

        }
    }
}
} 

我在这里提到的 Text_1.txt 文件是这样的

86.0

25.0

30.0

18.0

90.0

88.0

70.0

87.0

55.0

这里所说的数组 arr[] 就是要与键值进行比较的值。 arr[] 由 86.0 组成,文件有 86.0,所以搜索成功。该文件有 25.0,arr 也有值 25.0。于是再次搜索成功。该文件有一个值 30.0 但 arr[] 没有它。所以搜索不成功。

这是概念,但为什么它会进入无限循环。欢迎任何建议和讨论。

【问题讨论】:

  • first=mid+1,不是最后一个
  • 此外,它仅在数组 (arr) 已排序时才有效。

标签: java arrays file java.util.scanner binary-search


【解决方案1】:

首先,应该对应用二分搜索的数组进行排序!

您应该始终尝试可视化您的算法。对于二分搜索,你必须想象你有 2 个左右边界,左边界向右移动,右边界向左移动,这个过程一直持续到它们发生碰撞,或者直到你找到你的元素。

对我来说很明显你甚至没有尝试追踪你的算法......

另外,请注意您在另一个内部有一个 while 循环。而且你永远不会在第一个循环开始时重置你的第一个和最后一个变量。这是错误的。

最后一件事,比起(last + first) / 2,更喜欢first + (last - first) / 2。因为,(last + first) / 2 可以溢出,而first + (last - first) / 2 不能。

让我们把你的程序分解成两个函数,一个执行二分查找,另一个读取。

1)

static boolean binarySearch(double a) {
    double[] arr = {1, 2, 3, 4, 5, 6};
    Arrays.sort(arr);
    int first = 0;
    int last = arr.length - 1;

    while (first <= last) {
        int mid = first + (last - first) / 2;
        if (arr[mid] == a) {
            return true;
        } else if (arr[mid] < a) {
            first = mid + 1;
        } else /*if (arr[mid] > a)*/{
            last = mid - 1;
        }
    }
    return false;
}

2)

public static void main(String... args) {
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext()) {
        double d = sc.nextDouble();
        binarySearch(d);
    }
}

另外,JDK中有一个binarySearch方法,所以你的代码变成了:

public static void main(String... args) {
    Scanner sc = new Scanner(System.in);
    double[] arr = {1, 2, 3, 4, 5, 6};
    Arrays.sort(arr);
    while (sc.hasNext()) {
        double d = sc.nextDouble();
        Arrays.binarySearch(arr, d);
    }
}

【讨论】:

  • 如果我想使用未排序的数组,那么哪种搜索算法有用?
  • @Saswati 二进制搜索不适用于未排序的数组。你必须排序,否则你会得到意想不到的结果。请阅读en.wikipedia.org/wiki/Binary_search_algorithm
  • 我知道二进制搜索只适用于排序数组。我想知道是否有其他搜索算法适用于未排序的数组?
  • @Saswati 1) 有线性搜索,即 O(N).2) 您也可以将元素放入 HashSet 集合中,然后调用 set.contains(x),这样可以在 O(1) 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
  • 2021-10-22
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多