我正在尝试在java中编写快速合并排序。我基本上复制了维基百科页面中的代码,但出于某种原因我似乎无法使其工作。我确定我看到了一些小错误,但我似乎无法找到它。
public static void mergeSort(double[] array, double[] temp, int first, int last)
{
if( last - first < 2)
{// if the length of subarray is 1 return the array.
return;
}// else you recurse.
int mid = (first + last)/2;
mergeSort(array, temp,first, mid);// recursively split the array
mergeSort(array, temp, mid , last);
merge(array,temp,first,mid,last);// merge the sorted halves
copyArray(array, temp, first, last);
}// end of method merge sort
private static void merge(double[] array, double[] temp, int first, int mid ,int last)
{
// left half is A[first...mid-1]
// right half is A[mid...last -1]
int index0 = first, index1 = mid;
for(int i = first; i < last;i++)
{
if(index0 <= mid && (index1 <= last || array[index0] <= array[index1]))
{
temp[i]= array[index0];
index0+=1;
}
else
{
temp[i] = array[index1];
index1+=1;
}// end else
}// end for
}// end of method merge
public static void copyArray(double[] array, double[]temp, int first, int last)
{
for(int i = first;i< last;i++)
{
array[i] = temp[i];
}// end for
}// end of method copyArray
这是我的输入
double [] array = {7,4,9,3,4,1,6,8,2,5};
double [] temp = new double[10];
mergeSort(array, temp, 0, 10);
System.out.println(Arrays.toString(array));
这是我的输出。
[7.0, 4.0, 9.0, 9.0, 3.0, 1.0, 1.0, 6.0, 8.0, 8.0]
有什么想法可以让它像这样加倍?