In given array of elements like [a1,a2,a3,..an,b1,b2,b3,..bn,c1,c2,c3,...cn] Write a program to merge them like [a1,b1,c1,a2,b2,c2,...an,bn,cn].
Sample Testcases:
Input #00:
{1,2,3,4,5,6,7,8,9,10,11,12}
Output #00:
{1,5,9,2,6,10,3,7,11,4,8,12}
Explanation:
Here as you can notice, the array is of the form
{a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4}
/ swapArray.cpp : Defines the entry point for the console application.
ReplyDelete//
#include "stdio.h"
#include "conio.h"
#define N 12
int get_index(int idx, int len)
{
return (idx % 3) * len + (idx / 3);
}
void swap(int *i, int*j)
{
int temp=*i;
*i=*j;
*j=temp;
}
void swapArray(int A[N])
{
int len=N/3,i;
for(i=0;i<N;i++)
{
int new_idx= get_index(i,len);
while(new_idx < i)
{
new_idx = get_index(new_idx,len);
}
//printf("%d %d\n", i, new_idx);
swap(&A[i], &A[new_idx]);
}
for (i=0;i<N;i++)
{
printf("%d ", A[i]);
}
}
int main()
{
int A[N]={1,2,3,4,5,6,7,8,9,10,11,12};
swapArray(A);
getch();
return 0;
}