使用 C++ 将数组按最小值、最大值、次最小值、次最大值……的顺序重新排列


给定一个数组,我们需要按以下顺序排列此数组:第一个元素是最小元素,第二个元素是最大元素,第三个元素是次最小元素,第四个元素是次最大元素,以此类推,例如:

Input : arr[ ] = { 13, 34, 30, 56, 78, 3 }
Output : { 3, 78, 13, 56, 34, 30 }
Explanation : array is rearranged in the order { 1st min, 1st max, 2nd min, 2nd max, 3rd min, 3rd max }

Input : arr [ ] = { 2, 4, 6, 8, 11, 13, 15 }
Output : { 2, 15, 4, 13, 6, 11, 8 }

解决方法

这个问题可以使用两个变量'x'和'y'来解决,它们分别指向最大和最小元素。但为此,数组必须先排序,所以我们需要先对数组进行排序。然后创建一个相同大小的新空数组来存储重新排序的数组。现在迭代数组,如果迭代元素的索引为偶数,则将arr[x]元素添加到空数组中,并将x加1。如果元素的索引为奇数,则将arr[y]元素添加到空数组中,并将y减1。重复此操作,直到y小于x。

示例

#include <bits/stdc++.h>
using namespace std;
int main () {
   int arr[] = { 2, 4, 6, 8, 11, 13, 15 };
   int n = sizeof (arr) / sizeof (arr[0]);

   // creating a new array to store the rearranged array.
   int reordered_array[n];

   // sorting the original array
   sort(arr, arr + n);

   // pointing variables to minimum and maximum element index.
   int x = 0, y = n - 1;
   int i = 0;

   // iterating over the array until max is less than or equals to max.
   while (x <= y) {
   // if i is even then store max index element

      if (i % 2 == 0) {
         reordered_array[i] = arr[x];
         x++;
      }
      // store min index element
      else {
         reordered_array[i] = arr[y];
         y--;
      }
      i++;
   }
   // printing the reordered array.
   for (int i = 0; i < n; i++)
      cout << reordered_array[i] << " ";

   // or we can update the original array
   // for (int i = 0; i < n; i++)
   // arr[i] = reordered_array[i];
   return 0;
}

输出

2 15 4 13 6 11 8

以上代码的解释

  • 变量初始化为x=0 和 y = array_length(n) - 1
  • while(x<=y) 遍历数组直到x大于y。
  • 如果计数为偶数 (x),则将元素添加到最终数组中,并将变量x加1。
  • 如果 i 为奇数,则将元素 (y) 添加到最终数组中,并将变量 y 减 1。
  • 最后,重新排序的数组存储在 reordered_array[] 中。

结论

在这篇文章中,我们讨论了解决将给定数组重新排列成最小值、最大值形式的方案。我们还为此编写了一个 C++ 程序。类似地,我们可以用其他任何语言(如 C、Java、Python 等)编写此程序。我们希望您觉得这篇文章对您有所帮助。

更新于:2021年11月26日

609 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.