我试图弄清楚为什么以下代码不进行合并排序。代码编译良好,没有运行时错误。SortCollection 方法只返回一个未排序的数组。没有编译错误,也没有运行时错误,只返回一个未排序的数组。任何指针都会非常感激。
#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;
}
};