我坚持使用这种合并排序方法。我不是试图递归地做,但我不能让这个为我工作。我认为需要做一些微小的改变才能让它发挥作用。有什么建议?
protected static void merge(long[] a, long[] workSpace, int lowPtr, int highPtr, int upperBound) {
int j = 0; // workspace index
int lowerBound = lowPtr;
int mid = highPtr-1;
int n = upperBound-lowerBound+1; // # of items
while(lowPtr <= mid && highPtr <= upperBound)
if(a[lowPtr] < a[highPtr] )
workSpace[j++] = a[lowPtr++];
else
workSpace[j++] = a[highPtr++];
while(lowPtr <= mid)
workSpace[j++] = a[lowPtr++];
while(highPtr <= upperBound)
workSpace[j++] = a[highPtr++];
for(j=0; j<n; j++)
a[lowerBound+j] = workSpace[j];
答案 0 :(得分:0)
我怀疑它与你如何在外部使用这个例程有关。我在5分钟后盯着它看不到错误,所以我测试了它似乎工作正常。
你不需要知道c ++(这就是我碰巧在这台机器上有一个方便的编译器)
int main() {
long a[10] = {1,2,3,4,15,5,11,12,13,14}; // two sorted halves to merge
long * temp = new long[10];
for (int i = 0; i < 10; i++)
{
cout << a[i] << ","; // printout before merge
}
cout << endl;
merge(a, temp, 0, 5, 9); // 0-4 and 5-9
for (int i = 0; i < 10; i++)
{
cout << a[i] << ","; // printout after merge
}
}
输出:
1,2,3,4,15,5,11,12,13,14,
1,2,3,4,5,11,12,13,14,15,
更多的输出只是为了说服你:
1,2,6,14,15,5,11,12,32,100,
1,2,5,6,11,12,14,15,32,100,
1,2,100,143,1500,5,112,121,320,1000,
1,2,5,100,112,121,143,320,1000,1500,
12,20,100,143,179,5,12,121,320,430,
5,12,12,20,100,121,143,179,320,430,