I need to sort either the odd or even numbers in an array while leaving the rest unchanged. As this is part of a memory management course, I would strongly prefer not to duplicate any data so I didn't go for the obvious solution.

I thought about using a simple bubble sort function by skipping the "bad" first or second params of the comparison. I will post the function only as the rest is irrelevant.

```
//these are passed as sort_type_remainder
#define REMAINDER_EVEN 0
#define REMAINDER_ODD 1

void sort_integers(int *integer_list, int num_integers, int sort_type_remainder)
{
    int i, j, aux, offset = 1;
    for(i = 0; i < num_integers - 1; i++)
    {
        offset = 1;
        for(j = 0; j + offset < num_integers - i; j++)
        {
            if(abs(integer_list[j] % 2) != sort_type_remainder) //first element to be compared is of wrong type, skip
            {
                j++;
            }
            else
            {
                //first element is of good type, but second element is not, increase offset and reloop first element
                if(abs(integer_list[j + offset] % 2) != sort_type_remainder)
                {
                    j--;
                    offset++;
                }
                else //both elements are of good type, bubble sort them
                {
                    if(integer_list[j] > integer_list[j + offset])
                    {
                        aux = integer_list[j + offset];
                        integer_list[j + offset] = integer_list[j];
                        integer_list[j] = aux;
                    }
                    offset = 1;
                }
            }
        }
    }
}

```

This kind of works but some inputs are not processed properly and I can not figure out why. I tried reducing the input size to get a simpler way to reproduce this but as soon as I do so it starts working properly.

Here is the input / output, I deleted the even numbers as they stay in their position and it makes the error easier to notice.

```
odd
20
13 5 -3 4 2 -7 23 -33 1 6 -8 7 10 -51 9 -5 12 92 69 55

```

[![output](https://i.stack.imgur.com/9cxRB.png)](https://i.stack.imgur.com/9cxRB.png)

Any help or suggestions would be greatly appreciated, preferably with an explanation not just a solution.

Edit:: full program is here, don't want to clutter the question <http://pastebin.com/vZDcmppV>