DS内排—2-路归并排序

2023-07-30 13:55:26 浏览数 (1)

题目描述

输入一组字符串,用2-路归并排序按字典顺序进行降序排序。

输入

测试次数t

每组测试数据:数据个数n,后跟n个字符串,字符串不含空格。

输出

对每组测试数据,输出2-路归并排序的每一趟排序结果。每组测试数据的输出之间有1空行。

输入样例1 

2 6 shenzhen beijing guangzhou futian nanshan baoan 10 apple pear peach grape cherry dew fig haw lemon marc

输出样例1

shenzhen beijing guangzhou futian nanshan baoan shenzhen guangzhou futian beijing nanshan baoan shenzhen nanshan guangzhou futian beijing baoan pear apple peach grape dew cherry haw fig marc lemon pear peach grape apple haw fig dew cherry marc lemon pear peach haw grape fig dew cherry apple marc lemon pear peach marc lemon haw grape fig dew cherry apple

AC代码

代码语言:javascript复制
#include<iostream>
using namespace std;
string origin[256],done[256];
void Merge(int low,int mid,int high){
    int i=low,j=mid 1,k=low;
    while(i<=mid&&j<=high){
        if(origin[i]>=origin[j])
            done[k  ]=origin[i  ];
        else
            done[k  ]=origin[j  ];
    }
    while(i<=mid)
        done[k  ]=origin[i  ];
    while(j<=high)
        done[k  ]=origin[j  ];
}
int main() {
    int t,n,low,high,step,mid;
    cin>>t;
    while(t--){
        cin>>n;
        for(int i=0;i<n;i  )
            cin>>origin[i];
        for(step=1;step<n;step*=2){
            for(low=0;low<n;low =2*step){
                mid=low step-1;
                if(mid>n)
                    break;
                high=low 2*step-1;
                if(high>=n)
                    high=n-1;
                Merge(low,mid,high);
            }
            for(int i=0;i<n;i  )
                origin[i]=done[i];
            for(int i=0;i<n-1;i  )
                cout<<done[i]<<' ';
            cout<<done[n-1]<<endl;
        }
        cout<<endl;
    }
}

0 人点赞