使用 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.