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 <stdio.h>
int main(void)
{
int n,i,k,p,j,temp;
scanf("%d",&n);
int arr[n],arr_even[n],arr_odd[n];
k=0,p=0;
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
if(arr[i]%2==0) arr_even[k++]=arr[i];
else arr_odd[p++]=arr[i];
}
for(i=0;i<k;i++){
for(j=0;j<=i;j++){
if(arr_even[j]>arr_even[i]){
temp=arr_even[i],arr_even[i]=arr_even[j],arr_even[j]=temp;
}
}
}
for(i=0;i<p;i++){
for(j=0;j<=i;j++){
if(arr_odd[j]>arr_odd[i]){
temp=arr_odd[i],arr_odd[i]=arr_odd[j],arr_odd[j]=temp;
}
}
}
p=0;
for(i=0;i<n;i++)
{
if(k) arr[i]=arr_even[i],k--;
else arr[i]=arr_odd[p++];
}
for(i=0;i<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