我的合并排序代码中的合并函数有什么问题?

What is wrong the the merge function in my mergesort code?

对不起,初学者 here.This 我现在有:

public class MergeSort 
{
   public static void main(String[] args) 
    {
    int[] arr = {3, 5, 2, 4, 1};
    sort(arr, 0, arr.length - 1);
    for(int i = 0; i < arr.length; i++)
    {
        System.out.print(arr[i] + " ");
    }
}

private static void sort(int[] arr, int lo, int hi) 
{
    if(lo >= hi)
    {
        return;
    }
    int mid = (lo + hi)/2;

    sort(arr, lo, mid);
    sort(arr, mid + 1, hi);

    int size = hi - lo + 1;
    int[] temp = new int[size]; //new array to merge into

    merge(arr, temp, lo, mid + 1, hi);

    for(int i = 0; i < size; i++)
    {
        arr[i + lo] = temp[i];
    }
}

private static void merge(int[] arr, int[] temp, int lower, int mid, int upper) 
{
    int tempIndex = 0;
    int leftLo = lower;
    int leftHi = mid - 1;
    int rightLo = mid;
    int rightHi = upper;

    while(leftLo <= leftHi && rightLo <= rightHi)
    {
        if(arr[leftLo] < arr[rightLo])
        {
            temp[tempIndex] = arr[leftLo];
            tempIndex++;
            leftLo++;
        }
        else
        {
            temp[tempIndex] = arr[rightLo];
            tempIndex++;
            rightLo++;
        }
    }
}
 }

我知道是合并函数不起作用,因为现在它只打印出最小的元素,其余的为 0。我认为这与需要另一个 while 循环来复制数组有关,但我不知道如何编写它,甚至不知道它的目的,因为现在看来该数组正在合并到临时数组中以正确的顺序。为什么它只正确打印第一个元素?谢谢

merge 中,只要 leftLorightLo 都尚未达到其限制,您就可以复制值 。通常其中之一到达得早。然后你需要复制另一个的剩余值。您可以通过添加这两个循环来复制剩余的元素:

    while (leftLo <= leftHi) {
        temp[tempIndex] = arr[leftLo];
        tempIndex++;
        leftLo++;
    }
    while (rightLo <= rightHi) {
        temp[tempIndex] = arr[rightLo];
        tempIndex++;
        rightLo++;
    }

即完整方法变为:

private static void merge(int[] arr, int[] temp, int lower, int mid, int upper) {
    int tempIndex = 0;
    int leftLo = lower;
    int leftHi = mid - 1;
    int rightLo = mid;
    int rightHi = upper;

    while (leftLo <= leftHi && rightLo <= rightHi) {
        if (arr[leftLo] < arr[rightLo]) {
            temp[tempIndex] = arr[leftLo];
            tempIndex++;
            leftLo++;
        } else {
            temp[tempIndex] = arr[rightLo];
            tempIndex++;
            rightLo++;
        }
    }
    while (leftLo <= leftHi) {
        temp[tempIndex] = arr[leftLo];
        tempIndex++;
        leftLo++;
    }
    while (rightLo <= rightHi) {
        temp[tempIndex] = arr[rightLo];
        tempIndex++;
        rightLo++;
    }
}