标签:
没弄明白
#include<cstdio> #include<cstring> #include<cstdlib> #define MAXSIZE 10 //递归法 void Merge(int *list1,int list1_size,int *list2,int list2_size){ int i,j,k,m; int temp[MAXSIZE+1]; i = j = k = 0; while(i<list1_size && j<list2_size){ if(list1[i]<list2[j]){ temp[k++] = list1[i++]; }else{ temp[k++] = list2[j++]; } } while(i<list1_size){ temp[k++] = list1[i++]; } while(j<list2_size){ temp[k++] = list2[j++]; } for(m=0;m<list1_size+list2_size;m++){ list1[m] = temp[m]; } } void MergeSort(int k[],int n){ if(n>1){ int *list1 = k; int list1_size = n/2; int *list2 = k+n/2; int list2_size = n - list1_size; MergeSort(list1,list1_size); MergeSort(list2,list2_size); Merge(list1,list1_size,list2,list2_size); } } //非递归法 void MergeSort2(int k[],int n){ int i,left_min,left_max,right_min,right_max,next; int *temp = (int *)malloc(n*sizeof(int)); for(i=1;i<n;i*=2){ for(left_min = 0;left_min<n-i;left_min = right_max){ right_min = left_max = left_min + i; right_max = left_max + i; if(right_max>n){ right_max = n; } next = 0; while(left_min<left_max && right_min<right_max){ if(k[left_min]<k[right_min]){ temp[next++] = k[left_min]; }else{ temp[next++] = k[right_min]; } } while(left_min<left_max){ k[--right_max] = k[--left_max]; } while(next>0){ k[--right_min] = temp[--next]; } } } } int main(){ int a[10] = {9,1,5,8,3,7,4,6,2,10}; int i; MergeSort(a,10); for(i=0;i<10;i++){ printf("%d ",a[i]); } printf("\n"); return 0; }
标签:
原文地址:http://www.cnblogs.com/zhuozhuo/p/5451111.html