思想:
将有序表合并为一个大的有序表,有序表的规模一次为1,2,4,...
C代码
#include "stdio.h"
#include "stdlib.h"
void array_print(int a[],int n );
void sort_merge(int a[],int n);
int merge(int a[],int temp[],int start,int len,int n);
void main(){
int a[]={3,1,18,30,12,11,18,43,-1,-2,-100};
int n = sizeof(a)/sizeof(int);
sort_merge(a,n);
array_print(a,n);
}
void sort_merge(int a[],int n){
//merge sort use extra memory of same size for sorting
// make the size of merging double times
int *temp = (int*)malloc(n*sizeof(int));
int len = 1;
int i ;
while(len <= n){
i=0;
while(i<n)
i = merge(a,temp,i,len,n);
len *=2;
}
free(temp);
}
int merge(int a[],int temp[],int start,int len,int n){
int s1,e1,s2,e2,size_this_compare,i;
s1 = start;
e1 = start + len -1 ;
if( e1 >= n-1 )
return n;
s2 = e1 + 1;
e2 = s2+len-1 < n-1 ? s2+len-1 :n-1;
size_this_compare = e2 - s1 +1;
i=start;
while( s1<=e1 && s2<=e2){
while(s1<=e1 && a[s1]<=a[s2])
temp[i++] = a[s1++];
while(s2<=e2 && a[s2]<=a[s1])
temp[i++] = a[s2++];
}
while(s1<=e1) temp[i++] = a[s1++];
while(s2<=e2) temp[i++] = a[s2++];
while(i>=start){
i--;
a[i]=temp[i];
}
return e2+1;
}
void array_print(int a[],int n ){
int i;
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
Java代码
import java.util.ArrayList;
import java.util.List;
public class SortMerge implements Sort {
@Override
public void sort(List<Integer> source) {
int len =1;
int n = source.size();
while(len < n){
int s1,e1,s2,e2;
e2=-1;
while(true){
s1 = e2+1;
e1 = s1+len-1;
if(e1 >= n-1) break;
s2 = e1+1;
e2 = s2+len-1 < n-1 ? s2+len-1 : n-1;
merge(source, s1, e1, s2, e2);
}
len *=2;
}
}
private void merge(List<Integer> source , int s1, int e1, int s2,int e2){
int t1=s1,t2=s2,i=0;
List<Integer> temp = new ArrayList<>();
while( t1<=e1 && t2<=e2){
while(t1<=e1 && source.get(t1)<=source.get(t2) ) {
temp.add(source.get(t1));
i++;
t1++;
}
while(t2<=e2 && source.get(t2)<=source.get(t1)){
temp.add(source.get(t2));
i++;
t2++;
}
}
while(t1<=e1){
temp.add(source.get(t1));
i++;
t1++;
}
while(t2<=e2){
temp.add(source.get(t2));
i++;
t2++;
}
i--;
while(i>=0){
source.set(e2, temp.get(i));
i--;
e2--;
}
}
}