18061 数的交换

**思路**:
1. **输入函数**: 从用户输入中读取10个整数并存储在数组中。
2. **交换函数**: 找到数组中的最小值和最大值,分别与第一个和最后一个元素交换。
3. **输出函数**: 输出数组中的所有元素。

**伪代码**:
1. **输入函数**:
   - 使用循环读取10个整数并存储在数组中。
2. **交换函数**:
   - 初始化最小值和最大值的索引为0。
   - 遍历数组,找到最小值和最大值的索引。
   - 交换最小值与第一个元素,最大值与最后一个元素。
3. **输出函数**:
   - 使用循环输出数组中的所有元素。

**C代码**:

#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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值