18061 数的交换

**思路**:

  1. **输入函数**: 从用户输入中读取10个整数并存储在数组中。

  2. **交换函数**: 找到数组中的最小值和最大值,分别与第一个和最后一个元素交换。

  3. **输出函数**: 输出数组中的所有元素。

**伪代码**:

  1. **输入函数**:
  • 使用循环读取10个整数并存储在数组中。
  1. **交换函数**:
  • 初始化最小值和最大值的索引为0。

  • 遍历数组,找到最小值和最大值的索引。

  • 交换最小值与第一个元素,最大值与最后一个元素。

  1. **输出函数**:
  • 使用循环输出数组中的所有元素。

**C代码**:

cpp 复制代码
#include <stdio.h>

void input(int a[])
{
    for(int i = 0; i < 10; i++)
    {
        scanf("%d", &a[i]);
    }
}

void swap(int a[])
{
    int minIndex = 0, maxIndex = 0;
    for(int i = 1; i < 10; i++)
    {
        if(a[i] < a[minIndex])
            minIndex = i;
        if(a[i] > a[maxIndex])
            maxIndex = i;
    }
    // Swap the minimum value with the first element
    int temp = a[0];
    a[0] = a[minIndex];
    a[minIndex] = temp;
    
    // If the maximum value was at the first position, update its index
    if(maxIndex == 0)
        maxIndex = minIndex;
    
    // Swap the maximum value with the last element
    temp = a[9];
    a[9] = a[maxIndex];
    a[maxIndex] = temp;
}

void display(int a[])
{
    for(int i = 0; i < 10; i++)
    {
        printf("%d\n", a[i]);
    }
}

int main()
{
    int a[10];
    input(a);
    printf("input done\n");
    swap(a);
    printf("swap done\n");
    display(a);
    printf("display done\n");
    return 0;
}
相关推荐
XiaoHu02071 天前
C++特殊类设计与类型转换
开发语言·c++
大大大大物~1 天前
JVM 之 垃圾回收算法及其内部实现原理【垃圾回收的核心问题有哪些?分别怎么解决的?可达性分析解决了什么问题?回收算法有哪些?内部怎么实现的?】
jvm·算法
报错小能手1 天前
STL——set
开发语言·c++
不夜牛仔1 天前
算法笔记19 - 图和通用结构 | 图的两种遍历 | 三种拓扑排序 | 两种最小生成树算法Kruskal, Prim | 最短路径算法Dijkstra
笔记·算法
小龙报1 天前
【算法通关指南:基础算法篇】高精度专题:一篇破除超数运算问题
c语言·数据结构·c++·算法·链表·贪心算法·visual studio
ULTRA??1 天前
Informed RRT*算法,并包含圆形障碍物环境
人工智能·python·算法
汪宁宇1 天前
MFC基于CStatic自绘控件多轴+图样+标签的折线图控件
c++·mfc·标签·曲线图·多轴·图样
Yupureki1 天前
《算法竞赛从入门到国奖》算法基础:入门篇-双指针
c语言·开发语言·数据结构·c++·算法·visual studio
AshinGau1 天前
权重衰减(Weight Decay)
神经网络·算法
Liangwei Lin1 天前
洛谷 P3367 【模板】并查集
算法