kxf951
kxf951

Reputation: 155

Unique sort order of array c++

How would I sort an array of integers (0,1,2,3,4,5) in a monge shuffle type order (greatest odd to least odd, then least even to greatest even) like (5,3,1,0,2,4). Im having trouble trying to solve this problem.

Ive tried so far:

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++;
        }
    }
}

Upvotes: 2

Views: 318

Answers (2)

Mankarse
Mankarse

Reputation: 40623

You need to shuffle based on the indices being even or odd, not the values.

#include <iostream>

void mongeShuffle(int A[], int B[], int size)
{
    for(int i = 0; i < size; ++i)
    {
        if(i % 2 == 0)
        {
            B[(size+i)/2] = A[i];
        }
        else
        {
            B[size/2 - i/2 - 1] = A[i];
        }
    }
}

Upvotes: 2

Vikas
Vikas

Reputation: 8948

In c++ you can use algorithm header to use sort function and supply your custom comparator. Something like this:

#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;
    }
}

Upvotes: 4

Related Questions