繁体   English   中英

合并排序算法不起作用

[英]Mergesort algo not working

我正在尝试实现无法正常工作的mergesort算法。 合并排序的工作方式如下:

一世。 将未排序的列表划分为n个子列表,每个子列表包含1个元素(将1个元素的列表视为已排序)。

ii。 重复合并子列表以产生新排序的子列表,直到仅剩1个子列表为止。 这将是排序列表。 下面提供了实现。

最初,递归调用此方法,直到只有一个元素为止。

public void mergeSort(int low, int high) {

    if (low >= high) {
        return;
    }

    int middle = (low + high) / 2;

    // recursion for the merge
    mergeSort(low, middle);
    mergeSort(middle + 1, high);

    merge(low, middle, high);
}

这是提供的合并方法。

private void merge(int low, int middle, int high) {

    int i = low, j = middle;
    int index = low;

    for (int k = 0; k <= high; k++) {
        tempArray[k] = nums[k];
    }

    /*
      Copy the smallest values from either the left
      or the right side back to the original array
     */
    while ((i <= middle) && (j <= high)) {
        if (tempArray[i] <= tempArray[j]) {
            nums[index++] = tempArray[i++];
        } else {
            nums[index++] = tempArray[j++];
        }
    }

    // fill the left side of the array
    while (i < middle) {
        nums[index++] = tempArray[i++];
    }

    // fill the right side of the array
    while (j < high) {
        nums[index++] = tempArray[j++];
    }
  }

这是什么问题?

输入为int[] arr = {12, 3, 4, 56, -7, 1}; 输出为12 12 12 12 56 56

我修改了合并功能,它现在开始工作。 特别是, j需要在中间项j = middle+1之后初始化

 private void merge(int low, int middle, int high) {

    int i = low, j = middle+1;
    int index = low;

    for (int k = 0; k <= high; k++) {
        tempArray[k] = nums[k];
    }

    /*
      Copy the smallest values from either the left
      or the right side back to the original array
     */
    while ((i <= middle) && (j <= high)) {
        if (tempArray[i] <= tempArray[j]) {
            nums[index++] = tempArray[i++];
        } else {
            nums[index++] = tempArray[j++];
        }
    }

    // fill the left side of the array
    while (i <= middle) {
        nums[index++] = tempArray[i++];
    }

    // fill the right side of the array
    while (j <= high) {
        nums[index++] = tempArray[j++];
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM