我一直在研究合并排序递归代码,并且遇到了减速带。我已经通过互联网和我的算法本身在纸上浏览了很多次,但我似乎无法找出问题所在。
public static int[] mergesort(int[] data, int low, int high)
{
int middle = (high+low)/2;
if (middle==low)
{
int[] data2 = new int [1];
data2[0]=data[middle];
return data2;
}
else
{
int[] firstHalfSorted = mergesort(data, low, middle);
int[] secondHalfSorted = mergesort(data, middle+1, high);
return (merge(firstHalfSorted, secondHalfSorted));
}
}
public static int[] merge(int[] firstHalfSorted, int[] secondHalfSorted)
{
int[] SortedArray = new int[firstHalfSorted.length+secondHalfSorted.length];
int m = 0;
int n = 0;
int count = 0;
while (m<firstHalfSorted.length && n<secondHalfSorted.length)
{
if (firstHalfSorted[m]>secondHalfSorted[n])
{
SortedArray[count]=secondHalfSorted[n];
count++;
n++;
}
else if (firstHalfSorted[m]<secondHalfSorted[n])
{
SortedArray[count]=firstHalfSorted[m];
count++;
m++;
}
}
if (m!=firstHalfSorted.length)
{
while(m<firstHalfSorted.length){
SortedArray[count]=firstHalfSorted[m];
count++;
m++;
}
}
if (n!=secondHalfSorted.length)
{
while(n<secondHalfSorted.length){
SortedArray[count]=secondHalfSorted[n];
count++;
n++;
}
}
return SortedArray;
}
有代码。问题来自一个带有数字的文本输入文件,3,9,7,2,10,5,1,8 按此顺序排列,代码只对其他数字进行排序,分别是 3,7 和 10,1,然后是 3, 7,1,10。
根据我的所有想法,它应该排序 3,9 然后 7,2 等等,然后 3,9,7,2 和 10,5,1,8 等等,但它没有!你们能帮我吗?