排序问题 C++

排序问题


题目描述

输入10个整数,将它们从小到大排序后输出,并给出现在每个元素在原来序列中的位置。

输入描述

输入数据有一行,包含10个整数,用空格分开。

输出描述

输出数据有两行,第一行为排序后的序列,第二行为排序后各个元素在原来序列中的位置。

样例

输入

1 2 3 5 4 6 8 9 10 7

输出

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

来源

C语言实验6-一维数组的应用

C++实现

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
	int a[11][2];
	int i,j,temp;
	for(i=1;i<11;i++){
		cin>>a[i][0];
		a[i][1]=i;
	}
	
	for(i=1;i<11;i++) {
		for(j=i+1;j<11;j++){
			if(a[i][0]>a[j][0]){
				temp=a[i][0]; a[i][0]=a[j][0],a[j][0]=temp;
				temp=a[i][1]; a[i][1]=a[j][1],a[j][1]=temp;
			}
		}
	}
	for(j=0;j<2;j++) {
		for(i=1;i<10;i++) {
			cout<<a[i][j]<<" ";
		}
		cout<<a[10][j]<<endl;
	}
	return 0;
}

或用结构体实现

#include <iostream>
#include <algorithm>
using namespace std;

struct Nums{
	int num;
	int index;
}nums[10];

bool cmp(Nums a, Nums b){
	return a.num<b.num;
}

decltype(0) main()
{
	int j=1;
	for(int i=0;i<10;i++){
		cin>>nums[i].num;
		nums[i].index=j++;
	}
	sort(nums,nums+10,cmp);
	for(int i=0;i<9;i++){
		cout<<nums[i].num<<" ";
	}
	cout<<nums[9].num<<endl;
	for(int i=0;i<9;i++){
		cout<<nums[i].index<<" ";
	}
	cout<<nums[9].index<<endl;
	return 0;
} 

题目来源:https://icpc.ldu.edu.cn/contests/2793/problems/13

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值