标签:合并排序
在第二章中难的算法不多,接下来我会把稍微复杂一点的算法整理一下
#include <iostream> using namespace std; void mergeSort(int *A,int left,int mid,int right) { int *L=new int[mid-left+1]; int *R=new int[right-mid+1]; int i,j; for(i=0;i<mid-left+1;i++) { L[i]=A[left+i]; } for (j=0; j<right-mid; j++) { R[j]=A[mid+j+1]; } i=0,j=0; int k=left; while(i<mid-left+1 && j<right-mid) { if(L[i]<R[j]) { A[k++]=L[i++]; }else { A[k++]=R[j++]; } } while (i<mid-left+1) { A[k++]=L[i++]; } while (j<right-mid) { A[k++]=R[j++]; } delete []L; delete []R; } void merge(int *A,int left,int right) { if (left<right) { int mid=(right-left)/2+left; merge(A,left,mid); merge(A,mid+1,right); mergeSort(A,left,mid,right); } } int main(int argc, const char * argv[]) { int A[]={56,3,5,78,34,74,100,23,11,43,65}; //int A[]={56,3,5,68}; merge(A,0,sizeof(A)/sizeof(int)-1); for(int i=0;i<sizeof(A)/sizeof(int);i++) { cout<<A[i]<<" "; } cout << "\n"; return 0; }
标签:合并排序
原文地址:http://blog.csdn.net/richard_rufeng/article/details/25512319