DS内排—2-路归并排序

本文介绍了一种名为2-路归并排序的方法,用于将一组字符串按字典顺序进行降序排序。文章提供了输入样例、输出样例以及C++参考代码实现。
摘要由CSDN通过智能技术生成

DS内排—2-路归并排序

题目描述

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

输入

测试次数 t t t

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

输出

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

输入样例:

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

输出样例:

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

参考代码:

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

void display(string *arr, int len) {
    for (int i = 0; i < len; ++i) {
        cout << arr[i];
        if (i != len - 1)
            cout << ' ';
    }
    cout << endl;
}

void merge(string *arr, int left, int mid, int right) {
    queue<string> leftQueue, rightQueue;

    for (int i = left; i <= mid; i++) {
        leftQueue.push(arr[i]);
    }
    for (int i = mid + 1; i <= right; i++) {
        rightQueue.push(arr[i]);
    }

    int index = left;

    while (!leftQueue.empty() && !rightQueue.empty()) {
        if (leftQueue.front() < rightQueue.front()) {
            arr[index++] = rightQueue.front();
            rightQueue.pop();
        } else {
            arr[index++] = leftQueue.front();
            leftQueue.pop();
        }
    }

    while (!leftQueue.empty()) {
        arr[index++] = leftQueue.front();
        leftQueue.pop();
    }

    while (!rightQueue.empty()) {
        arr[index++] = rightQueue.front();
        rightQueue.pop();
    }
}

int main() {
    int T;
    cin >> T;
    while (T--) {
        int len;
        cin >> len;
        auto *arr = new string[len];
        for (int i = 0; i < len; ++i)
            cin >> arr[i];
        int size = 1, left, mid, right;
        while (size < len) {
            left = 0;
            while (left + size < len) {
                mid = left + size - 1;
                right = min(mid + size, len - 1);
                merge(arr, left, mid, right);
                left = right + 1;
            }

            display(arr, len);

            size *= 2;
        }

        cout << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鷸鰥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值