2

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++;
        }
    }
}
1
  • no were only allowed to use primitive functions Commented Oct 20, 2012 at 22:33

2 Answers 2

4

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;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

There is 6 elements in the array - not 5. The last else should be else return a%2 == 1...
4 test cases: both odd, both even, a is odd b is even, and a is even b is odd
@texasbruce, the 3rd and 4th test cases both are covered by return a%2 == 1
The question was unclear, but this code does not perform a Monge Shuffle. A Monge Shuffle is based on the indices of the cards, not the values.
@Mankarse, the question is ambiguous at this point. Based on OP's code, I thought he wants to sort similar to what Monge Shuffle does with indices. I'll remove it if OP clarifies or says this is not what he was looking for.
2

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

1 Comment

This really helped, but so far its working in opposite order such that: (0,1,2,3,4,5,6) would come out as (1,3,5,0,6,4,2) instead of (5,3,1,0,2,4,6)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.