归并排序
来源:互联网 发布:淘宝网店的等级 编辑:程序博客网 时间: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
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- ASP.NET AJAX Timer 控件概述
- 算法竞赛入门经典-前四章-UVa10071 - Back to High School Physics-重温高中物理-难度0
- 老程序员学C# ------操作DataGridView控件详解
- 倒序输出(2)
- iOS7应用开发16:模态segue、文本框、警告、Action Sheet
- 归并排序
- VirtualBox下linux与win7之间数据空间的建立
- R12供应商和银行
- Free buffer waits 等待事件总结
- 分治算法——快速排序
- FindFirstFile
- 参加广州网页平面UI设计培训让你成为企业精英
- 使用CGI进行远程编辑
- vim中NERDTree 的安装和使用