我想在java中編寫mergesort程序。不幸的是,我的實現給出了一個零列表作爲代碼的結果。我無法找到這個問題,因爲一切都看起來符合邏輯,並且對我來說是正確的。如果有人能幫我找到這個問題,我將不勝感激。java中的遞歸mergesort的小捻
的代碼如下:
package com.company;
public class Main {
public static void main(String[] args) {
int[] array = {35,43,21,4,23,1,13,44};
System.out.println("initial array is equal to:");
for (int data:array) {
System.out.println(data);
}
mergeSort(array, new int[array.length], 0, array.length-1);
System.out.println("Sorted array is equal to: ");
for (int s:array) {
System.out.println(s);
}
// arr = {35,43,21,4,23,1,13,44}
}
public static void mergeSort(int[] array,int[] secondaryArray,int leftStart, int rightEnd){
if(leftStart >= rightEnd){
return;
}
int midPoint = (leftStart + rightEnd)/2;
//sorting the left array
mergeSort(array, secondaryArray, leftStart, midPoint);
//sorting the right array
mergeSort(array, secondaryArray, midPoint+1, rightEnd);
//merging the sorted left and right array
mergeHalves(array, secondaryArray,leftStart, rightEnd);
}
public static void mergeHalves(int[] array, int[] secondaryArray, int leftStart, int rightEnd){
int leftEnd = (leftStart + rightEnd)/2;
int rightStart = leftEnd + 1;
int index = 0;
while ((leftStart <= leftEnd) && (rightStart <= rightEnd)){
if(array[leftStart] <= array[rightStart]){
secondaryArray[index] = array[leftStart];
leftStart++;
}else {
secondaryArray[index] = array[rightStart];
rightStart++;
}
index++;
}
System.arraycopy(array,rightStart,secondaryArray,index,rightEnd-rightStart+1);
System.arraycopy(array,leftStart,secondaryArray,index,leftEnd-leftStart+1);
System.arraycopy(secondaryArray,0,array,0,secondaryArray.length);
}
}
你應該做一些調試。 –