我想弄清楚爲什麼下面的代碼不會做合併排序。代碼編譯得很好,沒有運行時錯誤。 SortCollection方法只返回一個未排序的數組。沒有編譯錯誤和沒有運行時錯誤,只是返回一個未排序的數組。任何指針都會受到極大的關注。Visual C++合併排序
#include "stdafx.h"
#include <deque>
#include <climits>
#include <stdio.h>
using namespace System;
using namespace System::Collections;
using namespace System::Collections::Generic;
generic <typename T> where T: IComparable<T>
ref class MergeSort
{
public:
// constructor
MergeSort(){}
// SortCollection() method
array<T>^ SortCollection(array<T>^ inputArray)
{
int n = inputArray->Length;
if (n <= 1)
{
return inputArray;
}
array<T>^ array1 = gcnew array<T>(inputArray->Length/2);
array<T>^ array2 = gcnew array<T>(inputArray->Length - array1->Length);
int array1Count = 0;
int array2Count = 0;
for (int i = 0; i < n; i++)
{
if (i < n/2)
{
array1[array1Count] = inputArray[i];
array1Count++;
}
else
{
array2[array2Count] = inputArray[i];
array2Count++;
}
}
SortCollection(array1);
SortCollection(array2);
array<T>^ newArray = gcnew array<T>(inputArray->Length);
delete inputArray;
return Merge(newArray, array1, array2);
}
array<T>^ Merge(array<T>^ targetArray, array<T>^ array1, array<T>^ array2)
{
int n1 = array1->Length;
int n2 = array2->Length;
int x1 = 0;
int x2 = 0;
int counter = 0;
while (x1 < n1 && x2 < n2)
{
if (array1[x1]->CompareTo(array2[x2]) < 0)
{
targetArray[counter] = array1[x1];
x1 ++;
counter++;
}
else
{
targetArray[counter] = array2[x2];
x2 ++;
counter++;
}
}
while (x1 < n1)
{
targetArray[counter] = array1[x1];
counter ++;
x1 ++;
}
while (x2 < n2)
{
targetArray[counter] = array2[x2];
counter ++;
x2 ++;
}
return targetArray;
}
};
非常感謝,你的建議解決了我的問題。顯然更高效。我試圖弄清楚,爲什麼它在我重新使用原始數組時工作,但在傳遞相同大小的新數組時不起作用。如果你有一個想法,我會欣賞一點額外的理解! – deadEddie 2013-02-17 02:06:08
@deadEddie你打印/測試什麼? ..見編輯 – qPCR4vir 2013-02-18 09:50:49