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;
}
相关推荐
不知天地为何吴女士几秒前
Day32| 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
算法
小坏坏的大世界1 分钟前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
liulilittle1 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap
励志要当大牛的小白菜3 小时前
ART配对软件使用
开发语言·c++·qt·算法
qq_513970443 小时前
力扣 hot100 Day56
算法·leetcode
PAK向日葵4 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱装代码的小瓶子5 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
爱喝矿泉水的猛男6 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展
YuTaoShao6 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
YouQian7726 小时前
Traffic Lights set的使用
算法