编写程序:输入三个整数,然后按由大到小的顺序输出这三个数。

方法一(直接交换)

cpp 复制代码
#include<stdio.h>
int main()
{
	int a,b,c;
	scanf("%d%d%d",&a,&b,&c); 
	//可以这么写 想办法把a换成最大的数 ,之后是b c
	int temp;
	if(a<b)
	{
		temp=a;
		a=b;
		b=temp;
	 } 
	 if(a<c)
	 {
	 	temp=a;
		a=c;
		c=temp;
	 }
	 if(b<c)
	 {
	 	temp=b;
		b=c;
		c=temp;
	 }
	 printf("排序后的三个数为:%d %d %d\n",a,b,c);
	return 0;
}

方法二(冒泡排序思想)

cpp 复制代码
#include<stdio.h>
int main()
{
	int a[3];
	for(int i=0;i<3;i++)
	{
		scanf("%d",&a[i]);
	}
	for(int i=0;i<3-1;i++)
	{
		for(int j=0;j<3-i-1;j++)
		{
			if(a[j]<a[j+1])
			{
				int temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp;
			}
		}
	}
	 printf("排序后的三个数为:");
	 for(int i=0;i<3;i++) printf("%d ",a[i]);
	return 0;
}

延伸到对n个数排序

这里还是使用冒泡排序的思想

cpp 复制代码
#include<stdio.h>
int main()
{
	int n,a[1005];
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
	}
	for(int i=0;i<n-1;i++)
	{
		for(int j=0;j<n-i-1;j++)
		{
			if(a[j]<a[j+1])
			{
				int temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp;
			}
		}
	}
	 printf("排序后的%d个数为:",n);
	 for(int i=0;i<n;i++) printf("%d ",a[i]);
	return 0;
}
相关推荐
2501_941864967 分钟前
科学方法论破解学习时间堆砌误区
学习
堕27411 分钟前
java数据结构当中的《排序》(一 )
java·数据结构·排序算法
初願致夕霞26 分钟前
Linux_进程
linux·c++
2302_8138062239 分钟前
【嵌入式修炼:数据结构篇】——数据结构总结
数据结构
Thera7771 小时前
【Linux C++】彻底解决僵尸进程:waitpid(WNOHANG) 与 SA_NOCLDWAIT
linux·服务器·c++
Wei&Yan1 小时前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
1024小神1 小时前
SVG标签中path路径参数学习
学习
wregjru1 小时前
【QT】4.QWidget控件(2)
c++
浅念-1 小时前
C++入门(2)
开发语言·c++·经验分享·笔记·学习
ZH15455891311 小时前
Flutter for OpenHarmony Python学习助手实战:面向对象编程实战的实现
python·学习·flutter