【问题标题】:Top down mergesort. Merge operation not clear自上而下的归并排序。合并操作不清楚
【发布时间】:2016-01-20 07:00:48
【问题描述】:

我正在学习自上而下的归并排序,并且开始了解递归部分。我见过几个实现,其中合并是通过一系列 while 循环完成的。

但是,在下面的实现中,合并操作是不同的,它是如何工作的还不清楚。它似乎只是在比较索引而不是实际元素(与我见过的其他实现不同)

     private void merge(int[] aux, int lo, int mid, int hi) {

        for (int k = lo; k <= hi; k++) {
            aux[k] = theArray[k]; 
        }

        int i = lo, j = mid+1;
        for (int k = lo; k <= hi; k++) {
            if (i > mid) {
                theArray[k] = aux[j++];
            }
            else if (j > hi) {
                theArray[k] = aux[i++];
            }
            else if (aux[j] < aux[i]) {
                theArray[k] = aux[j++];
            }
            else {
                theArray[k] = aux[i++];
            }
        }
    }

    private void sort(int[] aux, int lo, int hi) {
        if (hi <= lo) 
            return;
        int mid = lo + (hi - lo) / 2;
        sort(aux, lo, mid);
        sort(aux, mid + 1, hi);
        merge(aux, lo, mid, hi);
    }

    public  void sort() {
        int[] aux = new int[theArray.length];
        sort(aux, 0, aux.length - 1);
    }

以上代码假设全局变量theArray 存在。

【问题讨论】:

  • 不应该是 int[] aux = new int[theArray.Length]; (没有 -1),然后 sort(aux, 0, theArray.Length-1) ?

标签: java algorithm sorting mergesort


【解决方案1】:

这个merge 方法只使用一个循环而不是大多数实现中使用的3 个循环(至少我见过的大多数实现)。

前两个条件处理来自被合并的两个源数组之一的所有元素已经添加到合并数组的情况。这些条件通常由第一个循环之后的单独循环处理,并且不需要比较两个源数组中的元素。

        if (i > mid) { // all the elements between lo and mid were already merged
                       // so all that is left to do is add the remaining elements 
                       // from aux[j] to aux[hi]
            theArray[k] = aux[j++];
        }
        else if (j > hi) { // all the elements between mid+1 and hi were already merged
                           // so all that is left to do is add the remaining elements 
                           // from aux[i] to aux[mid]
            theArray[k] = aux[i++];
        }
        else if (aux[j] < aux[i]) { // both source arrays are not done, so you have to
                                    // compare the current elements of both to determine
                                    // which one should come first
            theArray[k] = aux[j++];
        }
        else {
            theArray[k] = aux[i++];
        }

【讨论】:

  • 您的解释有帮助。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 2016-09-19
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 2013-06-29
  • 1970-01-01
相关资源
最近更新 更多