void Merge(Element Array[], ArraySize s, ArraySize m, ArraySize n) ...{ //将分别有序的Array[s... m]和Array[m+1... n]归并为有序的Array[s... n] long i, j, k, b_s = s; Element *temp; temp = (Element*) malloc((n-s+1) *sizeof(Element)); for(i=m+1, k=0; s<=m && i<=n; k++) ...{ if(Array[s]<Array[i]) ...{ temp[k] = Array[s]; s++; } else ...{ temp[k] = Array[i]; i++; } } for(j=s; j<=m; j++, k++) temp[k] = Array[j]; for(j=i; j<=n; j++, k++) temp[k] = Array[j]; for(i=b_s, j=0; i<=n; i++, j++) Array[i] = temp[j]; if(temp) free(temp); } void MergeSort(Element Array[], ArraySize Count) ...{ long t =1, s, i; long c = Count -1; while(t < Count) ...{ s = t; t =2*s; i =0; while(i+t <= Count) ...{ Merge(Array, i, i+s-1, i+t-1); i = i+t; } if(i+s < Count) Merge(Array, i, i+s-1, c); } }
Flash排序
constint THRESHOLD =75; const CLASS_SIZE =75; /**//* minimum value for m */ void Flash(Element a[], ArraySize n,int m,int*ctr) ...{ /**//* declare variables */ int*l,nmin,nmax,i,j,nmove,nx; long c1,c2,flash,hold,k; /**//* allocate space for the l vector */ l=(int*)calloc(m,sizeof(int)); /**//***** CLASS FORMATION ****/ nmin=nmax=0; for (i=0 ; i < n ; i++) if (a[i] < a[nmin]) nmin = i; elseif (a[i] > a[nmax]) nmax = i; if ( (a[nmax]==a[nmin]) && (ctr==0) ) ...{ printf("All the numbers are identical, the list is sorted "); return; } c1=(long)(m-1.0)/(a[nmax]-a[nmin]) ; c2=a[nmin]; l[0]=-1; /**//* since the base of the "a" (data) array is 0 */ for (k=1; k < m ; k++) l[k]=0; for (i=0; i < n ; i++) ...{ k=(long)floor(c1*(a[i]-c2) );//下整 l[k]+=1; } for (k=1; k < m ; k++) l[k]+=l[k-1]; hold=a[nmax]; a[nmax]=a[0]; a[0]=hold; /**//**** PERMUTATION *****/ nmove=0; j=0; k=m-1; while ( nmove < n ) ...{ while ( j > l[k] ) ...{ j++; k=(long)floor(c1*(a[j]-c2) ) ; } flash=a[ j ] ; while ( j <= l[k] ) ...{ k=(long)floor(c1*(flash-c2)); hold=a[ l[k] ]; a[ l[k] ] = flash; l[k]--; flash=hold; nmove++; } } /**//**** Choice of RECURSION or STRAIGHT INSERTION *****/ for (k=0;k<(m-1);k++) if ( (nx = l[k+1]-l[k]) > THRESHOLD ) /**//* then use recursion */ ...{ Flash(&a[l[k]+1],nx,CLASS_SIZE,ctr); (*ctr)++; } else/**//* use insertion sort */ for (i=l[k+1]-1; i > l[k] ; i--) if (a[i] > a[i+1]) ...{ hold=a[i]; j=i; while (hold > a[j+1] ) a[j++]=a[j+1] ; a[j]=hold; } free(l); /**//* need to free the memory we grabbed for the l vector */ } void FlashSort(Element d[], ArraySize n) ...{ int m=n, ctr; Flash(d, n, m, &ctr); }