归并排序的思想是将排序队列拆分为子队列,对排好序的子队列进行合并。子队列的排序过程跟父队列排序是相同的问题,因此可以通过递归调用解决。当子队列拆分到长度等于1时,自然就是已排好序的队列。
归并排序符合分治策略的思想,基本可以分成三步:
分解:将问题划分为一些子问题,子问题的形式与原问题一样,只是规模更小。
解决:递归的求解出子问题。如果子问题的规模足够小,则停止递归,直接求解。
合并:将子问题的解组合成原问题的解。
python代码:
#coding:utf-8
import sys
def MergeSort(A, start, end):
if end - start > 1:
mid = int((start + end)/2)
MergeSort(A, start, mid)
MergeSort(A, mid, end)
Merge2(A, start, mid, end)
def Merge(A, start, mid, end):
l = A[start: mid]
r = A[mid: end]
l.append(sys.maxint)
r.append(sys.maxint)
j = 0
k = 0
for i in range(start, end):
if l[j] <= r[k]:
A[i] = l[j]
j += 1
else:
A[i] = r[k]
k += 1
def Merge2(A, start, mid, end):
l = A[start: mid]
r = A[mid: end]
j = 0
k = 0
for i in range(start, end):
if j == len(l):
A[i] = r[k]
k += 1
elif k == len(r):
A[i] = l[j]
j += 1
elif l[j] <= r[k]:
A[i] = l[j]
j += 1
else:
A[i] = r[k]
k += 1
A = [2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
print(A)
MergeSort(A, 0, len(A))
print(A)
输出:
[Running] python -u "e:\GitHub\IntroductionToAlgorithms\Python\Chapter2\MergeSort.py"
[2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[Done] exited with code=0 in 0.064 seconds
C++代码:
#include "MergeSort.h"
#include "Common.h"
#include <limits>
void MergeSort(int* a, int start, int end)
{
if (end - start > 1)
{
int mid = (start + end) / 2;
MergeSort(a, start, mid);
MergeSort(a, mid, end);
Merge2(a, start, mid, end);
}
}
void Merge(int* a, int start, int mid, int end)
{
int len1 = mid - start;
int len2 = end - mid;
int* l = new int[len1 + 1];
int* r = new int[len2 + 1];
int* p = a + start;
int* p1 = l, * p2 = r;
for (int i = 0; i < len1; i++)
{
*p1++ = *p++;
}
l[len1] = INT_MAX;
for (int i = 0; i < len2; i++)
{
*p2++ = *p++;
}
r[len2] = INT_MAX;
p = a + start;
p1 = l;
p2 = r;
for(int i = start; i < end; i++)
{
if (*p1 <= *p2)
{
*p++ = *p1++;
}
else
{
*p++ = *p2++;
}
}
delete[] l;
delete[] r;
}
void Merge2(int* a, int start, int mid, int end)
{
int len1 = mid - start;
int len2 = end - mid;
int* l = new int[len1];
int* r = new int[len2];
int* p = a + start;
int * p1 = l, * p2 = r;
for (int i = 0; i < len1; i++)
{
*p1++ = *p++;
}
for (int i = 0; i < len2; i++)
{
*p2++ = *p++;
}
p = a + start;
p1 = l;
p2 = r;
for (int i = start; i < end; i++)
{
if (p1 == l + len1)
{
*p++ = *p2++;
}
else if (p2 == r + len2)
{
*p++ = *p1++;
}
else if (*p1 <= *p2)
{
*p++ = *p1++;
}
else
{
*p++ = *p2++;
}
}
delete[] l;
delete[] r;
}
void TestMergeSort()
{
int a[] = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 };
int len = sizeof(a) / sizeof(int);
MergeSort(a, 0, len);
Print(a, len);
}
输出:
1 2 3 4 5 6 7 8 9 10
E:\GitHub\IntroductionToAlgorithms\C++\build\Debug\IntroductionToAlgorithms.exe (进程 29840)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .