#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void merge(int * array, int start, int middle, int end)
{
int nIter=0;
int nIter1=start; //a[start]...a[middle]
int nIter2=middle+1; //a[middle+1]...a[end]
int * tempArray=new int[end-start+1];
memset(tempArray, 0, (end-start+1)*sizeof(int));
while(nIter1 <= middle && nIter2 <= end) //访问到其中一段结束为止,另一段剩余部分则直接复制
{
if(array[nIter1]<=array[nIter2])
{
tempArray[nIter]=array[nIter1];
nIter1++;
}
else
{
tempArray[nIter]=array[nIter2];
nIter2++;
}
nIter++;
}
for(;nIter1<=middle;nIter1++, nIter++)
tempArray[nIter]=array[nIter1];
for(;nIter2<=end;nIter2++, nIter++)
tempArray[nIter]=array[nIter2];
int i=0;
for(; start+i<=end; i++)
array[start+i]=tempArray[i];
}
void merge_sort(int array[], int start, int end)
{
if(start==end)
return;
int middle=(end+start)/2;
merge_sort(array, start, middle);
merge_sort(array, middle+1, end);
merge(array, start, middle, end);
}
void print_array(int array[], int n)
{
int nIter=0;
for(; nIter<n; nIter++)
{
printf("%d ", array[nIter]);
}
printf("\n");
}
void main()
{
int array[]={0,30,155,1,80,300,170,40,99};
printf("before sort:\n");
print_array(array, 9);
merge_sort(array, 0, 8);
printf("after sort:\n");
print_array(array, 9);
}
归并排序所用的时间复杂度为:nlgn
空间复杂度为:n
编程时,注意技巧性的东西: 将两个已排序的数组进行合并;