归并

来源:互联网 发布:ubuntu镜像文件下载 编辑:程序博客网 时间:2024/04/27 18:31
package sort;


public class MergeSort {
     public void mergearray(int a[],int first,int mid,int last,int temp[]){//合并两个有序序列,合并后依然有序。
    int i=first;
    int j=mid;
    int m=mid+1;
    int n=last;
    int k=0;
    while(i<=j&&m<=n){
    if(a[i]<a[m]){
    temp[k++]=a[i++];
    }else{
    temp[k++]=a[m++];
    }
    }
    while(i<=j){
    temp[k++]=a[i++];
    }
    while(m<=n){
    temp[k++]=a[m++];
    }
    for(int p=0;p<k;p++){
    a[first+i]=temp[i];
    }
     }
     
     public void mergesort(int a[], int first, int last, int temp[]){ 
          if(first<last){
         int mid=(first+last)/2;
         mergesort(a, first, mid, temp);
         mergesort(a,mid+1,last,temp);//先分治在合并
         mergearray(a,first,mid,last,temp);//合并
          }  
     }
}
0 0
原创粉丝点击