今天学习递归,看了教程居然一下子没看懂,发现不好的教程真是毁人,特此记录一下好的教程。
首先要介绍如何将两个已排序的数组合并,因为这是递归排序的核心思想:首先要介绍如何将两个已排序的数组合并,因为这是递归排序的核心思想:
void merge_array(int a[], int first, int mid, int last, int temp[]){
int i=first;
int j=mid+1;
int k=0;
while(i<=mid && j<=last){
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=mid)
temp[k++]=a[i++];
while(j<=last)
temp[k++]=a[j++];
for(int m=0;m<k;m++){
a[first+m]=temp[m];
}
}
接下来我们把这个函数应用到归并排序函数中去,其实就是递归使用该核心函数。
void merge_sort(int a[],int first, int last, int temp[]){
if(first<last){
int mid=(first+last)/2;
merge_sort(a,first,mid,temp);
merge_sort(a,mid+1,last,temp);
merge_array(a,first,mid,last,temp);
}
}
我们可以发现合并有序数列的效率是比较高的,即merge_array的时间复杂度是O(n)。在merge_sort中我们将数列不断二分,因此执行merge_array的次数是logN次。所以最终我们归并排序的时间复杂度就是两者相乘,即O(NlogN)。