C语言实现普通归并排序

来源:互联网 发布:淘宝客话术 编辑:程序博客网 时间:2024/06/08 12:15
void merge_array(int a[],int first, int mid, int last, int temp[]){int i = first, j = mid + 1;int m = mid, n = last;int k = 0;while(i <= m && j <= n){if(a[i] <= a[j]){   temp[k++] = a[i++];}else{   temp[k++] = a[j++];}}while(i <= m){temp[k++] = a[i++];}while(j <= m){temp[k++] = a[j++];}for(i=0; i < k; i++){a[first + i] = temp[i];}}void mergesort(int a[], int first, int last, int temp[]){if(first < last){int mid = (first + last)/2;mergesort(a, first,mid, temp);  //取数组前一半进行mergesort,直到子数组只有一个元素mergesort(a, mid+1, last, temp); //取数组后一半进行mergesort,直到子数组只有一个元素merge_array(a, first, mid, last, temp);  //将两个有序数组合并在一起}}void main(){int array[6] = {4,3,10,82,2,1};int b[6] = {0};// b用作临时存储数组mergesort(array,0,5,b);for(int i=0;i<6;i++){printf("%d,",array[i]);}}

原创粉丝点击