简单选择排序

【id:382】【20分】A. DS排序--简单选择排序

时间限制1s

内存限制128MB

题目描述

给出一个数据序列,使用简单选择排序算法进行升序排序。

输入

第一行输入t,表示有t个测试示例
第二行输入n,表示第一个示例有n个数据(n>1)
第三行输入n个数据,都是正整数,数据之间用空格隔开
以此类推

输出

对每组测试数据,输出每趟排序结果。不同组测试数据间用空行分隔。

样例查看模式 

正常显示查看格式

输入样例1 <-复制

2
5
12 58 36 47 96
10
1 3 6 9 0 8 5 7 4 2

输出样例

12 58 36 47 96
12 36 58 47 96
12 36 47 58 96
12 36 47 58 96

0 3 6 9 1 8 5 7 4 2
0 1 6 9 3 8 5 7 4 2
0 1 2 9 3 8 5 7 4 6
0 1 2 3 9 8 5 7 4 6
0 1 2 3 4 8 5 7 9 6
0 1 2 3 4 5 8 7 9 6
0 1 2 3 4 5 6 7 9 8
0 1 2 3 4 5 6 7 9 8
0 1 2 3 4 5 6 7 8 9

// 简单选择排序

#include "iostream"

using namespace std;

const int N = 100010;

int arr[N] = {0};

int len;

void print() {
    for (int i = 0; i < len; ++i) {
        cout << arr[i];
        if (i < len - 1) cout << " ";
    }
    cout << endl;
}

// 找出第num小的数字
void select_sort(int num) {
    int idx = num;
    int number = arr[num];
    for (int i = num+1; i < len; i++) {
        if (arr[i] < number) {
            number = arr[i];
            idx = i;
        }
    }
    swap(arr[idx], arr[num]);
}

int main() {
    int t;
    cin >> t;
    while (t--) {
        cin >> len;
        for (int i = 0; i < len; i++) cin >> arr[i];
        // 选择排序只需要n-1趟排序即可完成排序
        for (int i = 0; i < (len-1); i++) {
            select_sort(i);
            print();
        }
        cout << endl;
    }
    return 0;
}

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值