在这个问题中,我们得到了一个大小为n的数组arr [],该数组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 << "改组前的数组: ";
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;
}改组前的数组: 5 1 6 4 3 8 Array after Reshuffling: 4 1 6 5 8 3