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;
}
相关推荐
__BMGT()16 分钟前
C++ QT 打开图片
前端·c++·qt
顾子茵35 分钟前
c++从入门到精通(五)--异常处理,命名空间,多继承与虚继承
开发语言·c++
冲帕Chompa1 小时前
图论part10 bellman_ford算法
数据结构·算法·图论
緈福的街口1 小时前
【leetcode】144. 二叉树的前序遍历
算法·leetcode
GG不是gg1 小时前
排序算法之基础排序:冒泡,选择,插入排序详解
数据结构·算法·青少年编程·排序算法
随意起个昵称2 小时前
【双指针】供暖器
算法
倒霉蛋小马2 小时前
最小二乘法拟合直线,用线性回归法、梯度下降法实现
算法·最小二乘法·直线
YueiL2 小时前
基于RK3588的智慧农场系统开发|RS485总线|华为云IOT|node-red|MQTT
c++·物联网·华为云·rk3588·rs485
二进制人工智能2 小时前
【OpenGL学习】(二)OpenGL渲染简单图形
c++·opengl
codists2 小时前
《算法导论(第4版)》阅读笔记:p82-p82
算法