要实现归并排序递归方法:
第一步:先将原来的数据表分成排好序的子表,然后调用合并函数对子表进行归并,使之成为有序表
例如有如下向量:
⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⑾ 25, 10, 7, 19, 3, 48, 12, 17, 56, 30, 21 / 25,10,7,19,3 48,12,17,56,30,21 / \ / 25,10 7,19,3 48,12,17 56,30,21 / \ / \ / \ / 25 10 7 19,3 ... ... ... ...
归并算法的划分子表和归并子表与原数据序列次序无关,因此算法的最坏情况,最坏情况和平均情况时间复杂度是一样的
#include <stdio.h> #include <stdlib.h> void Merge(int arr[], int beg, int mid, int end) { int i = beg; int j = mid + 1; int p = 0; int *ipa; ipa = (int*)malloc((end-beg+1) * sizeof(int)); if(!ipa) return; while(i <= mid && j <= end) { //ipa[p++] = (arr[i]<=arr[j])?arr[i++]:arr[j++]; if(arr[i] <= arr[j]) { ipa[p] = arr[i]; p++; i++; } else { ipa[p] = arr[j]; p++; j++; } } while(i<=mid) { ipa[p++] = arr[i++]; } while(j<=end) { ipa[p++] = arr[j++]; } for(p=0, i=beg; i<=end; p++, i++) { arr[i] = ipa[p]; } } void MergeSort(int arr[], int beg, int end) { int mid; if(beg < end) { mid = (beg + end)/2; MergeSort(arr, beg, mid); MergeSort(arr, mid+1, end); Merge(arr, beg, mid, end); } } int main() { int a[9] = {7,10,48,25,12,17,21,48,30}; printf("Before Merge Sort:\n"); for(int i=0; i<9; i++) { printf("%d ", a[i]); } printf("\n"); printf("After Merge Sort:\n"); MergeSort(a, 0, 8); for(int i=0; i<9; i++) { printf("%d ", a[i]); } printf("\n"); return 0; }
参考:http://jillzhang.cnblogs.com/
http://blog.csdn.net/cwj649956781/article/details/7409635
时间: 2024-10-13 10:24:04