算法-归并排序
归并排序简言之,假设一个数组分成两个有同序的小数组(1/2组),然后将二者合并。
递归的假设,将小组再假设分成两个有同序的小组(1/4组),然后合并二者。
递归。。。。
最后1/n组剩下一个数据了,两个1/n组合并。这应该easy哈。
递归实现如下:
/// <summary>
/// Merge Sort O(nlogn)
/// </summary>
/// <param name="arr"></param>
public static void MergeSort(int[] arr)
{
if (arr == null)
{
throw new ArgumentNullException();
}
MergeSort(arr, 0, arr.Length - 1);
}
private static void MergeSort(int[] arr, int first, int last)
{
if (arr == null)
{
throw new ArgumentNullException();
}
if (first < last)
{
int mid = (first + last) / 2;
// Split the original array to two small arrays,[first,mid] and [mid+1,last]
MergeSort(arr, first, mid);
MergeSort(arr, mid + 1, last);
// Merge two small arrays to an array
int index1 = first;
int index2 = mid + 1;
int[] tempArr = new int[last - first + 1];
int tempIndex = 0;
while (index1 <= mid && index2 <= last)
{
if (arr[index1] < arr[index2])
{
tempArr[tempIndex++] = arr[index1];
index1++;
}
else
{
tempArr[tempIndex++] = arr[index2];
index2++;
}
}
while (index1 <= mid)
{
tempArr[tempIndex++] = arr[index1];
index1++;
}
while (index2 <= last)
{
tempArr[tempIndex++] = arr[index2];
index2++;
}
tempIndex = 0;
while (tempIndex < tempArr.Length)
{
arr[first + tempIndex] = tempArr[tempIndex];
tempIndex++;
}
}
}
/// Merge Sort O(nlogn)
/// </summary>
/// <param name="arr"></param>
public static void MergeSort(int[] arr)
{
if (arr == null)
{
throw new ArgumentNullException();
}
MergeSort(arr, 0, arr.Length - 1);
}
private static void MergeSort(int[] arr, int first, int last)
{
if (arr == null)
{
throw new ArgumentNullException();
}
if (first < last)
{
int mid = (first + last) / 2;
// Split the original array to two small arrays,[first,mid] and [mid+1,last]
MergeSort(arr, first, mid);
MergeSort(arr, mid + 1, last);
// Merge two small arrays to an array
int index1 = first;
int index2 = mid + 1;
int[] tempArr = new int[last - first + 1];
int tempIndex = 0;
while (index1 <= mid && index2 <= last)
{
if (arr[index1] < arr[index2])
{
tempArr[tempIndex++] = arr[index1];
index1++;
}
else
{
tempArr[tempIndex++] = arr[index2];
index2++;
}
}
while (index1 <= mid)
{
tempArr[tempIndex++] = arr[index1];
index1++;
}
while (index2 <= last)
{
tempArr[tempIndex++] = arr[index2];
index2++;
}
tempIndex = 0;
while (tempIndex < tempArr.Length)
{
arr[first + tempIndex] = tempArr[tempIndex];
tempIndex++;
}
}
}
我发现这个归并也我写QuickSort快,我想我的快排写的有问题??? 我得研究一下了。