Partitioning and sorting even and odd numbers within an array I solved a problem where it was told to sort an array of numbers such that the even numbers are kept first and the odd numbers should follow. Moreover, the even numbers must be sorted in ascending order among them and the odd numbers as well. Only arrays can be used. My code is as follows , which works fine but it seems bit long to me. I wanted to know if there is anything I can do to shorten it and make it more readable.

#include &lt;stdio.h&gt;

int main(void)
{
    int n,i,k,p,j,temp;

    scanf("%d",&amp;n);

    int arr[n],arr_even[n],arr_odd[n];

    k=0,p=0;
    for(i=0;i&lt;n;i++){
        scanf("%d",&amp;arr[i]);
        if(arr[i]%2==0) arr_even[k++]=arr[i];
        else arr_odd[p++]=arr[i];
    }

    for(i=0;i&lt;k;i++){
        for(j=0;j&lt;=i;j++){
            if(arr_even[j]&gt;arr_even[i]){
                temp=arr_even[i],arr_even[i]=arr_even[j],arr_even[j]=temp;
            }
        }
    }

    for(i=0;i&lt;p;i++){
        for(j=0;j&lt;=i;j++){
            if(arr_odd[j]&gt;arr_odd[i]){
                temp=arr_odd[i],arr_odd[i]=arr_odd[j],arr_odd[j]=temp;
            }
        }
    }

    p=0;
    for(i=0;i&lt;n;i++)
    {
        if(k) arr[i]=arr_even[i],k--;
        else arr[i]=arr_odd[p++];
        }

    for(i=0;i&lt;n;i++)
    {
        printf("%d ",arr[i]);
    }

    return 0;
}


Input:

10    
0 5 1 2 3 4 6 12 10 9


Output:

0 2 4 6 10 12 1 3 5 9
Your code is quite complicated. The C standard library provides all the ingredients you need to sort an array. You just need to define a comparison function. All the rest is done by the qsort function from stdlib.h.

The comparison function should look like:

static int even_first(const void *a, const void *b) {
    int left = *(const int *)a;
    int right = *(const int *)b;

    int res = (left % 2 != 0) - (right % 2 != 0);
    if (res == 0)
        res = (left &gt; right) - (left &lt; right);
    return res;
}


The expressions of the form cond1 - cond2 may look strange at first, but they are commonly used in C code in comparison functions like this one.

The benefit over a naïve left - right is that no integer overflow can happen. Integer overflow is a common source of undefined behavior.

To make the code more readable, it's also possible to extract the basic integer comparison into a separate function:

static int compare(int a, int b) {
    return a &lt; b ? -1 : a &gt; b ? +1 : 0;
    // alternatively: return (a &gt; b) - (a &lt; b);
    // alternatively: return a &lt; b ? -1 : a &gt; b;
}


Then, the comparison function becomes:

static int even_first(const void *a, const void *b) {
    int left = *(const int *)a;
    int right = *(const int *)b;

    int res = compare(left % 2 != 0, right % 2 != 0);
    if (res == 0)
        res = compare(left, right);
    return res;
}


This form is much less of a brain twister than the above variant.