binarySort方法没有返回正确项目的问题

时间:2014-11-27 16:29:04

标签: java logic binary-search

所以,我试图让我的binarySearch工作,它不会返回正确的搜索项。有人有想法吗?它总是返回到项目附近。我知道问题特别是在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));   
    }
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

你需要从0开始返回mid + 1作为索引。

所以如果你有1,2,3元素,如果你试图找到2,它会返回1,因为数组[1]指向2.所以如果你返回2,那就意味着你在第二个位置找到了元素

答案 1 :(得分:0)

你的问题在于:

    if (found) 
        return mid;

假设你有一个数字为{1,2,3,4,5}的数组 根据数组索引获得分配的方式1将获得索引0,2将获得索引1,依此类推。

当您尝试搜索2并找到它时,mid(根据程序)的值保存数组中值2的索引。上面数组中的索引2是1.因此,您只需要返回项目本身而不是返回2的索引。

     if (found) 
        return list[mid];

我想说更好的设计是从二进制搜索例程中返回true / false来指示是否找到了该项。原因是你返回0的情况是你从来没有找到数组中的项目,如果0也包含在要搜索的值中,则会出现问题。

如果您尝试返回项目的索引而不是项目本身,那么您的程序将按预期运行,而不是找不到它的情况 - 它应该返回类似索引-1的值而不是0(有效的指数)。

      else
        return 0;