1 / 7

归并排序

归并排序. 1. 一次二路归并排序 void merge(elemtype x[],elemtype swap[],int k,int n) /* 对序列 x[0]--x[n-1] 进行一次二路归并排序,每个有序子序列的长度为 k */ { int I,j,l1,u1,l2,u2,m ; l1=0; m=0;. while(l1+k<=n-1) { l2=l1+k; u1=l2-1; u2=(l2+k-1<=n-1)?l2+k-1:n-1; for(I=l1,j=l2;I<=u1&& j<=u2 ;

Download Presentation

归并排序

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 归并排序 • 1.一次二路归并排序 • void merge(elemtype x[],elemtype swap[],int k,int n) • /*对序列x[0]--x[n-1]进行一次二路归并排序,每个有序子序列的长度为k*/ • { int I,j,l1,u1,l2,u2,m ; • l1=0; • m=0;

  2. while(l1+k<=n-1) • { l2=l1+k; • u1=l2-1; • u2=(l2+k-1<=n-1)?l2+k-1:n-1; • for(I=l1,j=l2;I<=u1&& j<=u2 ; • m ++) • { if(x[I].key<=x[j].key) • { swap[m]=x[I]; • I++; • }

  3. else{ • swap[m]=x[j]; • j++; • } • } • /*序列2已归并完,将序列1中剩余的记录顺序存放到数组swap中*/ • while(I<=u1) • { swap[m]=x[I]; • m++;

  4. I++; • } • /*序列1已归并完,将序列2中剩余的记录顺序存放到数组swap中*/ • while(j<=u2) • { swap[m]=x[j]; • m++; • j++; • } • l1=u2+1; • }

  5. /*将原始序列中不足二组的记录顺序存放到数组swap中*//*将原始序列中不足二组的记录顺序存放到数组swap中*/ • for(I=l1;I<n;I++,m++) • swap[m]=x[I]; • } • 2.二路归并排序 • void mergesort(elemtype x[], • elemtype swap[],int n) • /*用二路归并排序法对记录x[0]--x[n-1]排序*/

  6. { int I,k; • /*归并长度由1开始*/ • k=1; • while(k<n) • { merge(x,swap,k,n); • /*将记录从数组swap放回x中*/ • for(I=0;I<n;I++) • x[I]=swap[I]; • /*归并长度加倍*/ • k=k*2;

  7. } • }

More Related