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;
}
相关推荐
geovindu4 小时前
python:Logistic Regression
开发语言·后端·python·算法
geovindu5 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
derek19976 小时前
软考软件设计师:主键、传递依赖和冗余,三问其实是一件事
c语言·c++·计算机网络·软件工程·学习方法
凌冰_6 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
拂拉氏6 小时前
【知识讲解】 数据结构与算法-树状数组的认识
数据结构·算法·树状数组
艾莉丝努力练剑7 小时前
【AI大模型接入SDK】解决Unicode码转化以及界面变形问题
前端·c++·人工智能·学习·安全·架构
djjjx.7 小时前
Mysql数据库基础篇(十一):索引的常见操作、聚簇与非聚簇索引、为什么其他数据结构不能作为索引的底层结构
数据结构
ShineWinsu7 小时前
对于Qt:事件分发器以及事件过滤器的解析
c++·qt·面试·gui·客户端·事件过滤器·事件分发器
饮水桶_T9 小时前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博
悠仁さん9 小时前
【C++】unordered_map_set 模拟实现
开发语言·c++