归并排序

来源:互联网 发布:淘宝网店的等级 编辑:程序博客网 时间:2024/05/16 08:29

    归并排序,是用分治法的一个典型的例子。把一个数组分成两个,分别排序那两个子数组,然后归并成一个数组,其技巧在于归并的过程。用代码实现如下:

#include <stdio.h>#include <stdlib.h> #define SIZE_ARRAY_1 5#define SIZE_ARRAY_2 6#define SIZE_ARRAY_3 20void merge_sort(int a[], int p, int r);void showArray(int a[], int n);void main(){int array1[SIZE_ARRAY_1]={1,4,2,-9,0};int array2[SIZE_ARRAY_2]={10,5,2,1,9,2};int array3[SIZE_ARRAY_3];for(int i=0; i<SIZE_ARRAY_3; i++){array3[i] = (int)((40.0*rand())/(RAND_MAX+1.0)-20);}printf("Before sort, ");showArray(array1, SIZE_ARRAY_1);merge_sort(array1, 0, SIZE_ARRAY_1-1);printf("After sort, ");showArray(array1, SIZE_ARRAY_1);printf("Before sort, ");showArray(array2, SIZE_ARRAY_2);merge_sort(array2, 0, SIZE_ARRAY_2-1);printf("After sort, ");showArray(array2, SIZE_ARRAY_2);printf("Before sort, ");showArray(array3, SIZE_ARRAY_3);merge_sort(array3, 0, SIZE_ARRAY_3-1);printf("After sort, ");showArray(array3, SIZE_ARRAY_3);}void showArray(int a[], int n){if(n>0)printf("This array has %d items: ", n);elseprintf("Error: array size should bigger than zero.\n");for(int i=0; i<n; i++){printf("%d ", a[i]);}printf("\n");}/* merge: merge two sorted array into one. * Principle: Use L and R to store the two sorted array. * Select the smaller one from the beginning of L and R, and this one is * the smallest one unmerged. */void merge(int a[], int p, int q, int r){int n1=q-p+1;int n2=r-q;int *L=malloc(n1*sizeof(int));int *R=malloc(n2*sizeof(int));for(int i=0;i<n1;i++) {L[i]=a[p+i];}for(int i=0;i<n2;i++) {R[i]=a[q+1+i];}int i=0; // index of Lint j=0; // index of Rint k=p; // index of awhile(i<n1 && j<n2) {if(L[i]<=R[j]) {a[k]=L[i];i++;} else {a[k]=R[j];j++;}k++;}// copy the remaining to aif(i==n1) { for(int jj=0;jj<n2-j;jj++) {a[k+jj]=R[j+jj];}} else {for(int ii=0;ii<n1-i;ii++) {a[k+ii]=L[i+ii];}}}/* merge_sort * Principle: Divide array into two parts, sort each part and then  * merge the two parts into one sorted array.   */void merge_sort(int a[], int p, int r){if(p<r) {int q=(p+r)/2;merge_sort(a, p, q);merge_sort(a, q+1, r);merge(a, p, q, r);}}

    归并的过程,需要每次找出两个子数组中最小的一个元素,将其移动到结果数组中。因为两个子数组已经是排好序的,所以只需要比较两个子数组中最小的元素就可以了。一旦一个子数组中的元素都已移动到结果数组中,就不需要继续比较了,直接移动另一个子数组到结果数组中就行了。

   

0 0
原创粉丝点击