void InsertSort(int a[], int n) //插入排序
{
int i,j = 2;
int key;
for (j = 2; j < n; j++)
{
key = a[j]; //key为要比较的元素
i = j - 1;
while (i > 0 && a[i] > key) //如果j前面的元素a[i]大于key则后移a[i]
{
a[i + 1] = a[i];
i--;
}
a[i + 1] = key; //插入key
}
}
void MergeSort(int a[], int p, int r) //归并排序
{
int q;
if (p<r)
{
q = (p + r) / 2;
MergeSort(a, p, q);
MergeSort(a, q + 1, r);
Merge(a, p, q, r);
}
}
void Merge(int a[], int p, int q, int r) //将两个已经排序好的子序列a[p..q]和a[q+1..r]合并成一个大的有序序列a[p..r]
{
int n1 = q - p + 1;
int n2 = r - q;
int L[SIZE] = {0}, R[SIZE] = {0};
for (int i = p,k=1; i <= q; i++,k++)
L[k] = a[i]; //将a[p..q]复制到L[k]数组
for (int i = q + 1,k=1; i <= r; i++,k++)
R[k] = a[i]; //将a[q+1..r]复制到R[k]数组
int i,j,k;
for (i=1,j=1,k=p; i <= n1&&j <= n2; k++)
{
if (L[i] <= R[j])
a[k] = L[i++];
else
a[k] = R[j++];
}
if (i <= n1) //若R[k]数组先结束,则直接将L[k]数组的剩余的元素复制到a数组
{
for (int l = 0; l <= n1 - i; l++)
a[k + l] = L[i + l];
}
if (j <= n2) //若L[k]数组先结束,则直接将R[k]数组的剩余的元素直接复制到a数组
{
for (int l = 0; l <=n2 - j; l++)
a[k + l] = R[j + l];
}
}