这是我到目前为止所得到的,我一直试图对它进行排序,但无法做到。我的目标是尝试合并未排序的数组。首先通过递归排序数组的前半部分然后排序数组的后半部分,而不创建新的临时数组,然后将两个数组合并到一个临时数组中,并将其内容复制到原始数组。
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) {
}
}
答案 0 :(得分:0)
您需要根据索引设置大小。因为你将a.length传递给高,所以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);