我在对这个未排序的数组进行排序时遇到问题

I'm having trouble sorting this unsorted array

这是我到目前为止得到的,我一直在尝试对它进行排序,但未能成功。我的目标是尝试合并未排序的数组。在不创建新的临时数组的情况下,先对数组的前半部分进行递归排序,然后对数组的后半部分进行递归排序,然后将两个数组合并为一个临时数组,并将其内容复制到原始数组中。

class SortApp2{
public static void main(String[] args) throws Exception {
    int [] a = {23,13,11,9,71,54,332,15,6,4,77,9,48,21,33,41,51,77,76, 91, 3, 1};
    System.out.println("The unsorted array is: " );
    printArray(a, a.length);
} //end method main()

public static void mergeSort(int [] a , int lower, int upper) {
    int mid;
    if(lower < upper) { // if not base case
        mid = (upper + lower) / 2; //split into 2 subarrays
        mergeSort( a, lower, mid); //sort each half
        mergeSort(a, mid+1, upper);
        merge(a, lower, upper); // merge 2 sorted subarrays
    }//end if
}// end method mergeSort()
public static void printArray(int [] a, int size){
    for(int i=0; i<size; i++) {
        System.out.print(a[i] + " ");
        if((i+1)%11 == 0) // carriage return if true
            System.out.println();
    } // end for loop
    System.out.println();
}//end method printArray()

public static void merge(int [] a, int low, int high) {
    int mid = (low + high)/2;
    int[] a1 = new int[22];
    int[] a2 = new int[22];
    int[] a3 = new int[22];
    int a1size = mid - low +1, a2size = high -mid;
    for(int i = 0;i < a1size;i++)  // lower half of a in a1
        a1[i] = a[low + i];
    for(int i = 0; i <a2size;i++) // upper half of a in a2
        a2[i] = a [mid + 1 + i];
    mergeArr(a1, a2, a3, a1size, a2size);
    //merge a1 and a2 into a3, then put a3 back into a  = a3
    for(int k= 0; k <a1size + a2size; k++)
        a[low+k] = a3[k];


    }// end method merge()

private static void mergeArr(int[] a1, int[] a2, int[] a3, int a1size, int a2size) {


}

}

您需要根据索引设置大小。由于您将 a.length 传递给 high,因此 high 确实是一个结束索引。

分配 a1 和 a2 修复:

int[] a1 = new int[mid-low];
int[] a2 = new int[high-mid];

复制到 a2 修复:

    a2[i-mid] = a[i];

你可以合并回一个[]:

    mergeArr(a1, a2, a, a1size, a2size);