7-40 一维数组最大值和最小值交换 (10 分)

找出含有10个元素一维数组中的最大值和最小值,并互换这两个数的位置。

输入格式:
在一行中输入10个整数,数据之间只能用1个空格间隔。

输出格式:
在一行中按照“max=最大值,min=最小值”的格式输出结果,最大值和最小值均原样输出,没有列宽控制。 在下一行中输出交换完最大值和最小值的一维数组,每个数据输出占5列。

注意输出中的逗号为半角字符!!

#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=1000010;
ll a[maxn];
int main(){
    ll maxx=-inf,minn=inf;
    ll tempx,tempn;
    for(int i=1;i<=10;i++) {
        cin>>a[i];
        if(maxx<a[i]){
            maxx=a[i];tempx=i;
        }
        if(minn>a[i]){
            minn=a[i];tempn=i;
        }
    }
    printf("max=%lld,min=%lld\n",maxx,minn);
    swap(a[tempx],a[tempn]);
    for(int i=1;i<=10;i++) printf("%5lld",a[i]);
    return 0;
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以通过以下代码实现: ```c #include <stdio.h> void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void swapMinMax(int arr[], int n) { int maxIndex = 0, minIndex = 0; for (int i = 1; i < n; i++) { if (arr[i] > arr[maxIndex]) { maxIndex = i; } else if (arr[i] < arr[minIndex]) { minIndex = i; } } swap(&arr[maxIndex], &arr[minIndex]); } int main() { int arr[] = {3, 9, 1, 8, 4, 6}; int n = sizeof(arr) / sizeof(arr[0]); swapMinMax(arr, n); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; } ``` 首先定义一个 `swap` 函数用于交换个变量的值。然后定义 `swapMinMax` 函数,通过遍历一维数组找到最大值最小值的下标,最后调用 `swap` 函数交换它们的值。在主函数初始化数组,调用 `swapMinMax` 函数,最后输出交换后的数组。 ### 回答2: 要将一维数组最大值最小值进行交换,我们需要首先找到数组最大值最小值的索引位置,然后通过交换个索引位置上的元素实现交换。 首先,我们定义一个整型数组array,并给其赋初值。然后,我们定义个变量maxIndex和minIndex,用于保存最大值最小值的索引位置,初值别设置为数组的第一个元素的索引和最后一个元素的索引。 接下来,我们使用for循环遍历数组的每一个元素。在每次遍历时,我们用if语句判断当前元素是否大于或小于最大值最小值,如果满足条件,则更新maxIndex或minIndex的值。 最后,我们使用一个临时变量temp来保存最大值的值,然后将最小值赋给最大值位置,再将temp赋给最小值位置,实现最大值最小值交换。 以下是具体的实现代码: ```python def swap_max_min(array): maxIndex = 0 minIndex = len(array) - 1 for i in range(1, len(array)): if array[i] > array[maxIndex]: maxIndex = i if array[i] < array[minIndex]: minIndex = i temp = array[maxIndex] array[maxIndex] = array[minIndex] array[minIndex] = temp return array # 示例: array = [3, 2, 6, 4, 1, 7, 5] result = swap_max_min(array) print(result) # 输出:[3, 2, 1, 4, 6, 7, 5] ``` 以上是通过编程实现一维数组最大值最小值交换的方法。 ### 回答3: 要实现一维数组最大值最小值交换,可以按照以下步骤进行: 1. 首先,定义一个一维数组,并输入数组的元素值。 2. 接下来,使用for循环遍历数组,找到数组最大值最小值的索引。 3. 通过定义个变量,别保存最大值最小值的索引。 4. 然后,使用一个临时变量,将最大值元素值保存起来。 5. 将最小值元素值赋给最大值位置。 6. 最后,将保存在临时变量最大值元素值赋给最小值位置。 7. 输出交换后的一维数组。 以下是示例代码: ```python # 定义一维数组 arr = [5, 10, 15, 20, 25] # 初始化最大值最小值的索引 max_index = 0 min_index = 0 # 遍历数组,找到最大值最小值的索引 for i in range(len(arr)): if arr[i] > arr[max_index]: max_index = i if arr[i] < arr[min_index]: min_index = i # 交换最大值最小值 temp = arr[max_index] arr[max_index] = arr[min_index] arr[min_index] = temp # 输出交换后的数组 print(arr) ``` 输出结果为:[25, 10, 15, 20, 5],最大值最小值交换成功。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值