1.归并思路:
2.代码实现
#include<stdio.h>
#include<malloc.h>
void _MergeSort(int *a,int* tmp, int left, int right)
{
if (left >= right)
{
return;//递到区间只有一个元素时,即left=right时,即可返回;
}
int mid = (left + right) >> 1;
_MergeSort(a, tmp, left, mid);
_MergeSort(a, tmp, mid+1, right);
int begin1 = left;
int begin2 = mid + 1;
int end1 = mid;
int end2 = right;
int index = left;
while (begin1 <= end1 && begin2 <= end2)
{
if (a[begin1] <a[begin2])
{
tmp[index++] = a[begin1++];
}
else
{
tmp[index++] = a[begin2++];
}
}
while (begin1 <= end1)
{
tmp[index++] = a[begin1++];
}
while (begin2 <= end2)
{
tmp[index++] = a[begin2++];
}
int i = 0;
for (i = left; i <= right; i++)
{
a[i] = tmp[i];
}
}
void MergeSort(int *a, int n)
{
int *tmp = (int *)malloc(sizeof(int)*n);
_MergeSort(a, tmp, 0, n - 1);
free(tmp);
}
int main()
{
int a[10] = { 4, 6, 1, 9, 0, 3, 2, 7, 8 ,5};
int n = sizeof(a) / sizeof(int);
MergeSort(a, n);
int i = 0;
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
return 0;
}