【问题标题】:Using Binary Search to open up a space in an array at the correct index使用二分搜索在数组中正确索引处打开一个空间
【发布时间】:2017-02-14 09:27:49
【问题描述】:

我应该创建两种方法:第一种方法,bSearch,是一种二分搜索算法。第二种方法 insertInOrder 应该获取我们从 bSearch 方法获得的索引并在数组中找到该索引,通过移动该数组的所有其他元素在该索引处打开一个点,并将 key/int 插入到那个索引。

整数将从包含 25 个整数的文本文件中接收。我不会制作任何副本或额外的数组来执行此操作,我应该对 insertInOrder 方法中的索引进行编码然后解码。在这些方法中,key 将是从 ints 文件中读取的当前 int,count 将计算已接收到的 int 数量。我基本上是在构建自己的排序方法,不能调用任何外部方法,而且数组也不能随时乱序。

我已经填写了这些方法,但我的理解有些不稳定。我认为我的问题是在 bSearch 方法中,因为我不能让它返回除 0 之外的任何内容。我不能让它返回 mid 的新值,这是 key/int 应该的索引被插入。比你的帮助。代码如下:

    static void insertInOrder( int[] arr, int count, int key   )
    {
        int index=bSearch( arr, count, key ); 

        int encodedIndex = -(index+1);
        int decodedIndex = -(index+1);

        for (int i = index; i > 0; i--)
        {
            arr[i] = arr[i-1];
        }

        arr[index]=key; 
    }


    static int bSearch(int[] a, int count, int key)
    {
        int lo = 0;
        int hi = a.length-1;
        int index = 0;
        boolean found = false;
        while (!found && lo <= hi)
        {   
            int mid = lo + ((hi - lo) / 2);
            if (a[mid] == key)
            {
                found = true;
                index = mid;        
            }
            else if (a[mid] > key)
            {
                hi = mid -1;
            }
            else
            {
                lo = mid +1;
            }
        }   
        return index;
    }

【问题讨论】:

    标签: java arrays if-statement while-loop binary-search


    【解决方案1】:

    您的二进制搜索方法适用于预填充数组。

    问题是在插入数组的过程中,如果数组中不存在该值,则二进制搜索返回0,而不是提供正确的插入位置。

    在这种情况下,您可能需要跟踪数组中当前使用了多少值。这就是“计数”的价值吗?在这种情况下,您应该从 count 而不是最大长度开始您的“hi”值,并且如果您已经到达数组的末尾而没有找到值,则需要将 count 作为索引返回。

    更新:您可以使用此二分搜索返回插入位置。

        int lo = 0;
        int hi = count-1;
        int index = 0;
        boolean found = false;
        while (!found && lo < hi)
        {
            int mid = lo + ((hi - lo) / 2);
            if (a[mid] == key)
            {
                found = true;
                index = mid;
            }
            else if (a[mid] > key)
            {
                hi = mid;
                index = hi;
            }
            else
            {
                lo = mid +1;
                index = lo;
            }
        }
        return index;
    

    【讨论】:

    • 感谢您的帮助,我明白了。我在 insertInOrder 方法中的起点和终点是关闭的,而您对我的 bSearch 方法的修复帮助了我很多。
    猜你喜欢
    • 2020-06-26
    • 2021-08-23
    • 2014-04-14
    • 2013-08-07
    • 2017-04-16
    • 2021-12-15
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多