If the input array is – 1,4,3,8,6,5,7 the output should be – 4 8 6 1 3 5 7
I have one solution with insertion sort kind of thing.
void sortarrayinorder(int arr[],int size)
{
int i,j,tem,k;
for(i=1;i<size;i++)
{
for(j=0;j<i;j++)
{
if((arr[j]%2)!=0 && (arr[i]%2)==0)
{
tem=arr[j];
arr[j]=arr[i];
for(k =i;k>j;k--)
arr[k]=arr[k-1];
arr[k+1]=tem;
}
}
}
}
Can this problem be solved in a better way? The complexity of my solution is o(n2). Please provide a solution with lesser time complexity. No extra space is allowed.
You can do this in
O(n)with a two-pass approach, so long as you’re allowed to allocate a separate output buffer. On the first pass, detect and copy all even numbers. On the second pass, detect and copy all odd numbers.