C#实现MergeSort算法
public class MergeSortLearn
{
/// <summary>
/// 分治递归
/// </summary>
/// <param name="oriArray"></param>
/// <returns></returns>
public static double[] MergeSort(double[] oriArray)
{
//基本条件
if (oriArray.Length <= 1)
{
return oriArray;
}
int halfSize = oriArray.Length / 2;
double[] preHalf = oriArray.Take(halfSize).ToArray();
double[] afterHalf = oriArray.Skip(halfSize).Take(oriArray.Length - halfSize).ToArray();
double[] sortedPreHalf = MergeSort(preHalf);
double[] sortedAfterHalf = MergeSort(afterHalf);
return Merge(sortedPreHalf,sortedAfterHalf);
}
/// <summary>
/// 合并两个有序数组
/// </summary>
/// <param name="sortedA"></param>
/// <param name="sortedB"></param>
/// <returns></returns>
public static double[] Merge(double[] sortedA, double[] sortedB)
{
double[] result = new double[sortedA.Length + sortedB.Length];
int i = 0, j = 0;
for(int k = 0; k < result.Length; k++)
{
if (j == sortedB.Length)
{
result[k] = sortedA[i];
i++;
continue;
}
if (i == sortedA.Length)
{
result[k] = sortedB[j];
j++;
continue;
}
if ( sortedA[i] < sortedB[j])
{
result[k] = sortedA[i];
i++;
}
else
{
result[k] = sortedB[j];
j++;
}
}
return result;
}
}
#####
愿你一寸一寸地攻城略地,一点一点地焕然一新
#####