归并排序的实现

来源:互联网 发布:二战各国综合国力数据 编辑:程序博客网 时间:2024/06/07 23:53
主要是其中的一个MERGE(int v[],int low, int mid, int last)的实现,自己写了一个,抄了一个,自己对比看看哪个号呵呵,果然自己的不行啊。。
merge(int v[],int first, int mid ,int last){
    
int i,i1,i2;
    
int temp=first;
    
int temp2=mid;
    
int temp3;
    
int length=last-first;
    i
=0;
    
while(i<=length&&mid<=last&&first<temp2){
        
if(MER(v[first],v[mid])==v[first]){
                hold[i]
=v[first];
                first
++;
        }

        
else{
            hold[i]
=v[mid];
            mid
++;
        }

        i
++;
    }

    
if(first<temp2){int j,c;
        j
=last;
        c
=temp2-1;
        
for(;c>=first;j--,c--){
            v[j]
=v[c];
        }

    }

    temp3
=i;
    
for(i=0;i<temp3;i++)
    
{        v[temp]=hold[i];
    temp
++;}

}
 这个网上的,可以明显看出比我的由美多了,变量也用的少呵呵
void Merge(SeqList R,int low,int m,int high)
    {//将两个有序的子文件R[low..m)和R[m+1..high]归并成一个有序的
     //子文件R[low..high]
     int i=low,j=m+1,p=0; //置初始值
     RecType *R1; //R1是局部向量,若p定义为此类型指针速度更快
     R1=(ReeType *)malloc((high-low+1)*sizeof(RecType));
     if(! R1) //申请空间失败
       Error("Insufficient memory available!");
     while(i<=m&&j<=high) //两子文件非空时取其小者输出到R1[p]上
       R1[p++]=(R[i].key<=R[j].key)?R[i++]:R[j++];
     while(i<=m) //若第1个子文件非空,则复制剩余记录到R1中
       R1[p++]=R[i++];
     while(j<=high) //若第2个子文件非空,则复制剩余记录到R1中
       R1[p++]=R[j++];
     for(p=0,i=low;i<=high;p++,i++)
       R[i]=R1[p];//归并完成后将结果复制回R[low..high]
    } //Merge
原创粉丝点击