【问题标题】:why is this not executing in vs code editor?为什么这不在 vs 代码编辑器中执行?
【发布时间】:2021-11-09 04:11:02
【问题描述】:
public class binsearch {
public static void main(String args[])
{
    int arr[]={2,45,-21,56,23};
    int target=45;
    int answer=binarysearch(arr, target);
    System.out.println(answer);

}
static int binarysearch(int arr[],int target)
{

    int start=0;
    int end=arr.length-1;
    int mid=start+end/2;
    while(start<=end)
    {
    if(target<arr[mid])
    {
        mid=end-1;
    }
    else if(target>arr[mid])
    {
        mid=mid+1;
    }
    else
    {
        return mid;
    }
}
return -1;
}

}

我已尝试多次运行此代码,但它就是不运行。我认为这段代码中的二进制搜索逻辑没有任何问题。请帮忙。谢谢。

【问题讨论】:

    标签: java visual-studio-code


    【解决方案1】:

    您的代码运行。它有一个无限循环,所以它永远不会终止。

    为了使二分搜索工作。数组必须按升序排序。因此,只需在进行二进制搜索之前对数组进行排序。下面的代码使用类java.util.Arrays 对数组进行排序,但您可以随意排序。只需确保在进行二进制搜索之前对数组进行排序即可。

    另外,mid 的计算需要在 while 循环内进行,因为它的值总是由 startend 的值确定,而这些值在 @987654327 内更改@循环。

    请注意,我更改了类名以遵守Java naming conventions。这些约定使其他人更容易阅读和理解您的代码。

    import java.util.Arrays;
    
    public class BinSearch {
        static int binarysearch(int arr[], int target) {
            int start = 0;
            int end = arr.length - 1;
            while (start <= end) {
                int mid = start + ((end - start) / 2);
                if (target < arr[mid]) {
                    end = mid - 1;
                }
                else if (target > arr[mid]) {
                    start = mid + 1;
                }
                else {
                    return mid;
                }
            }
            return -1;
        }
    
        public static void main(String[] args) {
            int arr[] = {2, 45, -21, 56, 23};
            Arrays.sort(arr);
            int target = 45;
            int answer = binarysearch(arr, target);
            System.out.println(answer);
        }
    }
    

    answer 是 3,因为在排序之后,45 是 [sorted] 数组中倒数第二个元素,因为它是数组中的第二大数字。

    如果你想在不排序数组的情况下进行搜索,那么二进制搜索是不合适的。

    【讨论】:

    • 如果找不到元素,你的代码也会无限循环。
    • 感谢您提供如此详细的解释^_^
    • @RachelPeters 你可以接受我的回答来表达你的感激之情:-)
    猜你喜欢
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多