卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章19562本站已运行343

使用C++重新排列数组顺序 - 最小值、最大值、第二小值、第二大值

使用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 等)编写此程序。我们希望本文对您有所帮助。

卓越飞翔博客
上一篇: Go语言和PHP、Java开发效率对比:哪个更高?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏