数组中的排序问题

先输入5个数字

c++ 复制代码
#include<stdio.h>
int main(){
    int arr[5];
    for(int i = 0;i < 5;i++){
	scanf("%d",&arr[i]);
	}
    }

打印输出

c++ 复制代码
for(int i = 0;i < 5;i++){
    printf("%d",arr[i]);
	}

排序:5,3,2,6,4

交换:交换数组中的前面两个数的位置

含义:把下标为0的元素,和下标为1的元素交换一下位置

代码如下:

c++ 复制代码
#include<stdio.h>
int main(){
    int arr[5];
    int temp = arr[0];
    arr[0] = arr[1];
    arr[1] = temp;
    printf("%d",arr[0]);
    printf("%d",arr[1]); 
    }

结果如下:

把下标为 0 的元素先存在另一个变量中,再令下标为0和下标为1的元素相同,再将下标为1的元素与之前存的变量相等,就可以把两个元素交换位置

排序:通过比较相邻元素的大小,并交换,把最大的值放在数组的最后面

c++ 复制代码
#include<stdio.h>
int main(){
    for(int i = 0; i < 4;i++){
		for(int j = 0; j < 4;j++ ){
			if(arr[j] > arr[j+1]){
				int temp = arr[j];
				arr[j] = arr[j+1];
				arr[j+1] = temp;
		}
	}
}
	for(int i = 0 ;i < 5;i++){
		printf("%d\n",arr[i]);
	}

}

结果如下:

将三者整合起来

c++ 复制代码
#include<stdio.h>
int main(){
    int arr[5];
    for(int i = 0 ; i < 5 ; i++){
        scanf("%d",&arr[i]);
    }
    printf("-------------\n");
    
    for(int i = 0;i < 4;i++){
        for(int j = 0;j < 4;j++){
            if(arr[j] > arr[j+1]){
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;  
            }
        }
    }
    
    for(int i = 0;i < 5;i++){
        printf("%d",arr[i]);
    }


}

任意输入5个数字

结果如下

相关推荐
有时间要学习3 小时前
面试150——第五周
算法·深度优先
晚霞的不甘4 小时前
Flutter for OpenHarmony 可视化教学:A* 寻路算法的交互式演示
人工智能·算法·flutter·架构·开源·音视频
望舒5134 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
C++ 老炮儿的技术栈4 小时前
Qt 编写 TcpClient 程序 详细步骤
c语言·开发语言·数据库·c++·qt·算法
KYGALYX4 小时前
逻辑回归详解
算法·机器学习·逻辑回归
铉铉这波能秀4 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
踢足球09294 小时前
寒假打卡:2026-2-8
数据结构·算法
IT猿手5 小时前
基于强化学习的多算子差分进化路径规划算法QSMODE的机器人路径规划问题研究,提供MATLAB代码
算法·matlab·机器人
千逐-沐风5 小时前
SMU-ACM2026冬训周报3rd
算法
铉铉这波能秀5 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple