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;
}
相关推荐
浅念-3 分钟前
「一文吃透 BFS:从层序遍历到锯齿形、最大宽度、每层最大值」
数据结构·算法
汉克老师5 分钟前
GESP5级C++考试语法知识(十三、贪心算法(一))
算法·贪心算法·海盗船·gesp5级·gesp五级·排队接水
玩转单片机与嵌入式41 分钟前
玩转边缘AI(TInyML):需要掌握的C++知识汇总!
开发语言·c++·人工智能
历程里程碑1 小时前
4 Git远程协作:从零开始,玩转仓库关联与代码同步(带实操代码讲解)
大数据·c++·git·elasticsearch·搜索引擎·gitee·github
梦想画家1 小时前
Apache AGE实战指南:从Cypher语法到核心图算法
算法·cypher·apache age
刀法如飞1 小时前
Go数组去重的20种实现方式,AI时代解决问题的不同思路
后端·算法·go
汉克老师2 小时前
GESP5级C++考试语法知识(贪心算法(一)课堂例题精讲)
c++·贪心算法·gesp5级·gesp五级·贪心规律
墨染千千秋2 小时前
C++头文件的使用,和各个头文件与头文件用处
c++
呱呱巨基2 小时前
Linux 基础IO
linux·c++·笔记·学习
旖-旎2 小时前
深搜练习(N皇后)(10)
c++·算法·深度优先·力扣