1

I have created a small C program which sorts odd and even numbers in descending order, with the user inputting whether they wish to sort the odd or the even numbers. So in order to try and make it more complex, I was wondering if there was a way in which I could have my program sort only the even numbers while leaving the odd numbers in their current place and vice versa so for instance:

Input:

odd

1 7 3 5 2 4 20

Output:

1 3 5 7 2 4 20

There is probably multiple ways to go about this, I'm wanting to include it in

John Anderson
  • 17
  • 1
  • 8

3 Answers3

0

Maybe something like, if the number is divisible by 2(remainder 0) it is even, so do nothing. If the number + 1 is divisible by 2(and so is odd), then sort.

takintoolong
  • 140
  • 9
0

First of all you should place the sort algorithm in a separate function. Secondly you can add one more parameter that will specify the predicate for elements of the array that need to be sorted.

For example

#include <stdio.h>

void sort( int a[], size_t n, int predicate( int ) )
{
    for ( size_t i = 0; i < n; i++ )
    {
        if ( predicate( a[i] ) )
        {
            for ( size_t j = i + 1; j < n; j++ )
            {
                if ( predicate( a[j] ) && a[i] < a[j] )
                {
                    int tmp = a[i];
                    a[i] = a[j];
                    a[j] = tmp;
                }
            }
        }
    }
}   

int even( int x ) { return ( x & 1 ) == 0; }
int odd( int x ) { return ( x & 1 ); }

int main(void) 
{
    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
    putchar( '\n' );

    sort( a, N, even );

    for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
    putchar( '\n' );

    sort( a, N, odd );

    for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
    putchar( '\n' );

    return 0;
}

The program output is

0 1 2 3 4 5 6 7 8 9 
8 1 6 3 4 5 2 7 0 9 
8 9 6 7 4 5 2 3 0 1 
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

... sort only the even numbers while leaving the odd numbers in their current place and vice versa

When encountering a value that matches SkipType, skip that array element.

// Return true when odd, else false
bool IsOdd(int x) {
  return x%2;  // x%2 --> -1,0,1
}

...
// Select skipping odd or even
bool SkipType = IsOdd(1);

for (i = 0; i < ArraySize; ++i) {
  if (IsOdd(number[i]) == SkipType) continue;
  for (j = i + 1; j < ArraySize /*size*/; ++j) {
    if (IsOdd(number[j]) == SkipType) continue;
    if (number[i] > number[j]) {  // I think OP want > here, not <
      a = number[i];
      number[i] = number[j];
      number[j] = a;
    }
  }
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256