1)把0~length-1的数组分成左数组和右数组
2)对左数组和右数组进行迭代排序
3)将左数组和右数组进行合并,那么生成的整个数组就是有序的数据数组(关键)
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <malloc.h>
void merge(int *array, int start, int middle, int end)
{
int left = start;
int right = middle + 1;
int length = end - start + 1;
int *p = malloc(sizeof(int) * length);
assert(NULL != p);
int index = 0;
int i;
while(index < length)
{
while(left <= middle && right <= end)
{
if(array[left] <= array[right])
{
p[index] = array[left];
left ++;
index ++;
}
else
{
p[index] = array[right];
index ++;
right ++;
}
}
while(left <= middle)
{
p[index] = array[left];
left ++;
index ++;
}
while(right <= end)
{
p[index] = array[right];
index ++;
right ++;
}
}
for(i = 0; i < length; i ++)
printf("%d,", p[i]);
printf("
");
memmove(array + start, p, length * sizeof(int));
}
void _merge_sort(int *array, int start, int end)
{
int middle = start + ((end - start) >> 1);
if(start >= end)
return;
_merge_sort(array, start, middle);
_merge_sort(array, middle + 1, end);
merge(array, start, middle, end);
}
void merge_sort(int *array, int length)
{
assert(NULL != array || 0 != length);
_merge_sort(array, 0, length - 1);
}
void test()
{
int i;
int array[10] = {1,3,4,5,8,6,7,9,0,2};
merge_sort(array, 10);
for(i = 0; i < 10; i ++)
{
printf("%d, ", array[i]);
}
printf("
");
}
int main()
{
test();
}