21xrx.com
2025-03-28 05:42:47 Friday
文章检索 我的文章 写文章
如何在C++中交换数组的最大值和最小值
2023-07-13 07:55:44 深夜i     54     0
C++ 数组 最大值 最小值 交换

在C++中,交换数组的最大值和最小值是一项很重要的任务。对于很多程序员而言,可能不太清楚该如何去完成这项任务,下面将介绍如何在C++中完成该操作。

首先,我们需要定义一个整型数组,并对该数组进行初始化,如下所示:

int arr[] = 1;

接着,我们需要找到数组中的最大值和最小值,并记录它们的索引值,代码如下所示:

int n = sizeof(arr) / sizeof(arr[0]);
int maxIndex = 0, minIndex = 0;
for (int i = 0; i < n; i++) {
  if (arr[i] > arr[maxIndex])
    maxIndex = i;
  
  if (arr[i] < arr[minIndex])
    minIndex = i;
  
}

此时,我们已经找到了数组中的最大值和最小值,接下来就是将它们进行交换。使用一个变量来保存最大值,再将最小值覆盖最大值的位置,最后再将保存的最大值覆盖最小值的位置,最终完成交换操作,具体代码如下所示:

int temp = arr[maxIndex];
arr[maxIndex] = arr[minIndex];
arr[minIndex] = temp;

完整的代码如下:

#include <iostream>
using namespace std;
int main() {
  int arr[] = 3;
  int n = sizeof(arr) / sizeof(arr[0]);
  int maxIndex = 0, minIndex = 0;
  for (int i = 0; i < n; i++) {
    if (arr[i] > arr[maxIndex])
      maxIndex = i;
    
    if (arr[i] < arr[minIndex])
      minIndex = i;
    
  }
  int temp = arr[maxIndex];
  arr[maxIndex] = arr[minIndex];
  arr[minIndex] = temp;
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
  return 0;
}

运行代码将会输出:`1 3 2 5 4`,数组的最大值5和最小值1已经成功交换。

总的来说,在C++中交换数组的最大值和最小值要做的步骤有三个:

1. 找到数组中最大值和最小值的索引。

2. 将最大值和最小值进行交换。

3. 输出交换后的数组。

  
  

评论区

请求出错了