使用 C++ 将数组重新排列为最大最小形式


给定一个已排序的数组。我们需要将此数组重新排列为最大、最小形式,即第一个元素是最大元素,第二个元素是最小元素,第三个元素是第二大元素,第四个元素是第二小元素,依此类推,例如 -

Input : arr[ ] = { 10, 20, 30, 40, 50, 60 }
Output : { 60, 10, 50, 20, 40, 30 }
Explanation : array is rearranged in the form { 1st max, 1st min, 2nd max, 2nd min, 3rd max, 3rd min }

Input : arr [ ] = { 15, 17, 19, 23, 36, 67, 69 }
Output : { 69, 15, 67, 17, 36, 19, 23 }

有一种方法可以将数组重新排列为最大值和最小值形式 -

寻找解决方案的方法

有一种方法可以将数组重新排列为最大值和最小值形式 -

双指针法

使用两个变量 min 和 max,它们分别指向最大和最小元素,并创建一个相同大小的新空数组来存储重新排列的数组。现在迭代数组,如果迭代元素位于偶数索引处,则将 arr[max] 元素添加到空数组中,并将 max 减 1。如果元素位于奇数索引处,则将 arr[min] 元素添加到空数组中,并将 min 加 1。重复此操作,直到 max 小于 min。

示例

#include <bits/stdc++.h>
using namespace std;

int main () {
   int arr[] = { 1, 2, 3, 4, 5, 6 };
   int n = sizeof (arr) / sizeof (arr[0]);
   // creating a new array to store the rearranged array.
   int final[n];
   // pointing variables to initial and final element index.
   int min = 0, max = n - 1;
   int count = 0;
   // iterating over the array until max is less than or equals to max.
   for (int i = 0; min <= max; i++) {
      // if count is even then store max index element

      if (count % 2 == 0) {
         final[i] = arr[max];
         max--;
      }
      // store min index element
      else {
         final[i] = arr[min];
         min++;
      }
      count++;
   }
   // printing the final rearranged array.
   for (int i = 0; i < n; i++)
      cout << final[ i ] << " ";
   return 0;
}

输出

6 1 5 2 4 3

上述代码的解释

  • 变量初始化为 min=0 和 max = 数组长度(n) - 1。
  • for (int i = 0; min <= max; i++) 迭代数组,直到 max 大于 min。
  • 如果计数为奇数,则将 (max) 元素添加到最终数组中,并将变量 max 减 1。
  • 假设计数为偶数,则 (min)。在这种情况下,元素将添加到最终数组中,并且变量 min 将加 1。
  • 最后,结果数组存储在 final[ ] 数组中。

结论

在本文中,我们讨论了将给定数组重新排列为最大-最小形式的解决方案。我们讨论了解决方案的方法,并使用时间复杂度为 O(n) 的乐观解决方案解决了它。我们还为此编写了一个 C++ 程序。类似地,我们可以在其他任何语言(如 C、Java、Python 等)中编写此程序。我们希望您发现本文有所帮助。

更新于: 2021年11月26日

238 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.