C++中偶数位于偶数索引处,奇数位于奇数索引处


在这个问题中,我们得到一个大小为n的数组arr[],它包含n/2个偶数值和n/2个奇数值。我们的任务是编写一个程序,将偶数放在偶数索引处,奇数放在奇数索引处。

让我们举个例子来理解这个问题:

输入:arr[] = {5, 1, 6, 4, 3, 8}

输出:arr[] = {6, 1, 5, 4, 3, 8}

解决方案方法 -

一种解决方案是遍历数组,然后找到不在偶数位置的数字,并用下一个奇数位置的值替换它。这是一个可行的解决方案,但可以通过使用两个索引(一个用于偶数,一个用于奇数)来提高效率。如果偶数索引处有一个非偶数元素,并且奇数索引处有一个非奇数元素,我们将交换它们,否则将两个索引都增加二。

程序演示了我们解决方案的工作原理:

示例

在线演示

#include <iostream>
using namespace std;

void O_EReshuffle(int arr[], int n) {
   
   int oIndex = 1;
   int eIndex = 0;
   
   for(int i = 0; i < n; ) {
     
      while (eIndex < n && arr[eIndex] % 2 == 0)
         eIndex += 2;
         
      while (oIndex < n && arr[oIndex] % 2 == 1)
         oIndex += 2;
         
      if (eIndex < n && oIndex < n)
         swap (arr[eIndex], arr[oIndex]);
         
      else
         break;
   }
}

int main()
{
   int arr[] = { 5, 1, 6, 4, 3, 8 };
   int n = sizeof(arr) / sizeof(arr[0]);

   cout << "Array before Reshuffling: ";
   for(int i = 0; i < n ; i++){
      cout<<arr[i]<<"\t";
   }
   O_EReshuffle(arr, n);

   cout<<"\nArray after Reshuffling: ";
   for(int i = 0; i < n ; i++){
      cout<<arr[i]<<"\t";
   };

   return 0;
}

输出 -

Array before Reshuffling: 5 1 6 4 3 8
Array after Reshuffling: 4 1 6 5 8 3

更新于:2021年1月22日

947 次浏览

启动您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.