java - binarySort 方法未返回正确项目的问题

标签 java logic binary-search

所以,我试图让我的binarySearch 工作,但它没有返回正确的搜索项。有人有主意吗?但它总是返回接近该项目的值。我知道问题出在二元搜索方法中的 while 循环上。

public class Sort { 
    static int item;
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args) {
        int[] list = new int[500];
        for (int c = 0; c < 500; c++){
            Random r = new Random();
            list[c] = r.nextInt(1000);  
        }
        int l = list.length; 
        System.out.print("Enter a search element: ");
        System.out.println();
        item = console.nextInt();
        insertionSort(list, l);
    }
    public static int binarySearch(int[] list, int l, 
            int searchItem){
        int first = 0;
        int last = l - 1;
        int mid = 0;
        boolean found = false;

        while (first <= last && !found)
        {
            mid = (first + last) / 2;
            if (list[mid] == searchItem)
                found = true;
            else if (list[mid] > searchItem)
                last = mid - 1;
            else
                first = mid + 1;
        }
        if (found) 
            return mid;
        else
            return 0;
    }

    public static void insertionSort(int[] list,  int l){
        int first, location;
        int temp;
        for (first = 1; first < l; first++){
            if (list[first] < list[first - 1]){
                temp = list[first];
                location = first;
                do {
                    list[location] = list[location - 1];
                    location--;
                }
                while(location > 0 && list[location - 1] > temp);
                list[location] = temp;
            }
        }
        System.out.println(binarySearch(list, l, item));   
    }
}

感谢您的帮助!

最佳答案

您需要返回 mid + 1,因为索引从 0 开始。

因此,如果您有 1,2,3 个元素,并且如果您尝试查找 2,它将返回 1,因为 array[1] 指向 2。因此,如果您返回 2,则意味着您在第二个位置找到了该元素.

关于java - binarySort 方法未返回正确项目的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27175164/

相关文章:

python - 扩展逻辑语句(乘法)

c# - 将列表中小于 1% 的数字设置为 1%,同时保持总数为 100%

php - PHP 中的正则表达式二进制模式搜索

java - 在Java中的排序字符串数组中查找以指定字符串开头的第一个元素

java - 将数组列表写入文本文件

java - Apache httpclient HTTPGET 解码

Javascript 比较逻辑 - 让 a = 1 。 a === (3 || 1 ) 错误,为什么?

algorithm - 查找数组中两个数字之间的最小绝对差的最佳算法

java - 如何迭代 JavaFX 组合框?

JavaServlet : set an instance as an attribute