## 算法学习之合并排序

2010-10-30 20:02  MichaelYin  阅读(508)  评论(0编辑  收藏  举报

 //将两个数组按照顺序重新进行排列
public static void Merge(int[] rawArray, int firstIndex, int middleIndex, int lastIndex)
{
//把middle指向的元素划分到前面的一个数组去
int firstArrayCount = middleIndex - firstIndex + 1;
int secondArrayCount = lastIndex - middleIndex;

int[] firstArray = new int[firstArrayCount];
int[] secondArray = new int[secondArrayCount];

//将原来数组的元素分别复制到两个分开的数组当中去
for (int i = 0; i < firstArrayCount; i++)
{
firstArray[i] = rawArray[firstIndex + i];
}

for (int i = 0; i < secondArrayCount; i++)
{
secondArray[i] = rawArray[middleIndex + i + 1];
}

int firstArrayIndex = 0;
int secondArrayIndex = 0;
int rawArrayIndex = firstIndex;

//开始进行合并
//通过while条件判断是否有数组已经全部遍历完毕,如果已经有一个数组输出完毕那么会跳出while循环
while (firstArrayIndex < firstArrayCount && secondArrayIndex < secondArrayCount)
{
if (firstArray[firstArrayIndex] <= secondArray[secondArrayIndex])
{
//将值赋给原来的数组对应的位置，完毕后index都加1
rawArray[rawArrayIndex++] = firstArray[firstArrayIndex++];
}
else
{
rawArray[rawArrayIndex++] = secondArray[secondArrayIndex++];
}
}
//跳出while循环后，这时有一个数组已经全部输出完毕，由于另外一个数组一定是按大小排序的数组，所以将剩下的元素直接循环赋值到原来的数组中去\
while (firstArrayIndex < firstArrayCount)
{
rawArray[rawArrayIndex++] = firstArray[firstArrayIndex++];
}

while (secondArrayIndex < secondArrayCount)
{
rawArray[rawArrayIndex++] = secondArray[secondArrayCount++];
}
}

        /// <summary>
///
/// </summary>
/// <param name="rawArray">需要排序的数组</param>
/// <param name="firstIndex">左边界</param>
/// <param name="lastIndex">右边界</param>
public static void MergeSort(int[] rawArray, int firstIndex, int lastIndex)
{
if (firstIndex < lastIndex)
{
int middleIndex = (firstIndex + lastIndex) / 2;
//递归调用函数
MergeSort(rawArray, firstIndex, middleIndex);
MergeSort(rawArray, middleIndex + 1, lastIndex);
//合并
Merge(rawArray, firstIndex, middleIndex, lastIndex);
}
}