合并排序辅助数组创建/中间问题

时间:2019-10-30 06:13:18

标签: java

我对自己的代码有疑问。我在下面用---><---标记了它。

public class Main {
    public static void main(String[] args) {
        int[] arr = {5, 4, 3, 2, 1, 4, 5, 6, 7, 8, 10};
        int[] aux = new int[arr.length];
        sort(arr, aux, 0, arr.length - 1);

        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    public static void sort(int[] arr, int[] aux, int low, int high) {

        // what does these lines do? --->
        if (low >= high) { 
            return;
        }
        int mid = low + (high - low) / 2; // why cant it just be high - low / 2
        //<--- These lines

        sort(arr, aux, low, mid); //sorts left side
        sort(arr, aux, mid + 1, high); //sorts right side
        merge(arr, aux, low, mid, high); //merges the two sides
    }

    public static void merge(int[] arr, int[] aux, int low, int mid, int high) {
        for (int k = low; k <= high; k++) {
            aux[k] = arr[k];
        }
        //copies the array into an aux array

        int i = low; //counter for the left side
        int j = mid + 1; //counter for the right side

        for (int k = low; k <= high; k++) {
            if (i > mid) { //if i > mid meaning that if the left side of the array is empty then use the right side
                arr[k] = aux[j++];
            }
            else if (j > high) { //if j > high then right side of array has been used so use left
                arr[k] = aux[i++];
            }
            else if (aux[i] <= aux[j]) { //if value of left side is <= value of right then bring leftside value up to original array
                arr[k] = aux[i++];
            }
            else { //value of right side is <= value of left so bring rightside value up to original array
                arr[k] = aux[j++];
            }
        }
    }
}

这是GeeksForGeeks合并的一部分

void merge(int arr[], int l, int m, int r) { 
    /* Create temp arrays */
    // These lines --->
    int L[] = new int [n1]; 
    int R[] = new int [n2]; 
    //<---
}

使用G4Geek的临时数组:

  • 每次合并都创建一次吗?

  • 记忆只留在那里吗?

  • 当前代码是我更好的做法吗?

谢谢。

0 个答案:

没有答案