#include <stdio.h>
void mySwap(int *a, int i, int j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
void myPrint(int *a, int len)
{
int i;
for (i = 0; i < len; i++)
{
printf ("%4d", a[i]);
}
printf ("\n");
}
void merge(int *a, int left, int mid, int right, int *tmp)
{
int i = left; // 左半边数组下标
int j = mid+1; // 右半边数组下标
int k = 0; // 临时数组使用的下标
while(i<=mid && j<=right)
{
if (a[i] < a[j])
tmp[k++] = a[i++];
else
tmp[k++] = a[j++];
}
while(i<=mid)
{
tmp[k++] = a[i++];
}
while (j<=right)
{
tmp[k++] = a[j++];
}
for(i = 0; i < k; i++)
{
a[left+i] = tmp[i];
}
}
void mergeSort(int *a, int left, int right, int *tmp)
{
int mid = (left+right)/2;
if (left < right)
{
mergeSort(a, left, mid, tmp); // 对左边数组进行归并排序
mergeSort(a, mid+1, right, tmp); // 对右边数组进行归并排序
merge(a, left, mid, right, tmp); // 合并左右两个数组
}
}
int main()
{
int a[] = {5,8,6,7,9,4,3,2,1,0};
int len = sizeof(a)/sizeof(a[0]);
int tmp[10];
mergeSort(a, 0, len-1, tmp);
myPrint(a, len);
return 0;
}