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;
}
相关推荐
Magnum Lehar7 分钟前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎
水蓝烟雨40 分钟前
[面试精选] 0094. 二叉树的中序遍历
算法·面试精选
超闻逸事1 小时前
【题解】[UTPC2024] C.Card Deck
c++·算法
暴力求解1 小时前
C++类和对象(上)
开发语言·c++·算法
JKHaaa1 小时前
几种简单的排序算法(C语言)
c语言·算法·排序算法
让我们一起加油好吗1 小时前
【基础算法】枚举(普通枚举、二进制枚举)
开发语言·c++·算法·二进制·枚举·位运算
大锦终1 小时前
【C++】特殊类设计
开发语言·c++
FogLetter1 小时前
微信红包算法揭秘:从随机性到产品思维的完美结合
算法
泽02022 小时前
C++之STL--list
开发语言·c++·list
YGGP2 小时前
吃透 Golang 基础:数据结构之 Map
开发语言·数据结构·golang