gpt4 book ai didi

c++ - 数组c++的唯一排序顺序

转载 作者:搜寻专家 更新时间:2023-10-31 00:17:36 25 4
gpt4 key购买 nike

我如何按照 monge shuffle 类型的顺序(最大奇数到最小奇数,然后是最小偶数到最大偶数)对整数数组 (0,1,2,3,4,5) 进行排序,例如 (5,3, 1,0,2,4)。我在尝试解决这个问题时遇到了麻烦。

到目前为止我已经尝试过:

void mongeShuffle(int A[], int B[], int size)
{
int i = 0; // i is the index of the arr
while(i < size)
{
if(A[i] % 2 == 1)
{
B[i] = A[i];
i++;
}
else
{
B[i] = A[i -1];
i++;
}
}
}

最佳答案

c++ 中,您可以使用 algorithm header 来使用 sort 函数并提供自定义比较器。像这样:

#include <algorithm>
#include <iostream>

bool my_comp (int a, int b)
{
if( a%2 == 1 && b%2 == 1)
{
// Both odd
return a > b;
}
else if( a%2 == 0 && b%2 == 0)
{
// Both even
return a < b;
}
else return a%2 == 1;
}

int main()
{
int A[] = {0,1,2,3,4,5};
std::sort(A, A + 6, my_comp);

for(int i: A)
{
std::cout << i << std::endl;
}
}

关于c++ - 数组c++的唯一排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12986091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com