In a given array of elements like [a1, a2, a3, a4, ….. an, b1, b2, b3, b4, ……. bn, c1, c2, c3, c4, …….. cn] without taking a extra memory how to merge like [a1, b1, c1, a2, b2, c2, a3, b3, c3, ………… an, bn, cn]

void arrange(int arr[], int n, int i)
{
if(i == 1)
{
arr[1] = arr[n];
arr[2] = arr[n << 1];
return;
}
int j = i - 1;

int c = arr[(n << 1) + j];
int b = arr[n + j];
int a = arr[j];

arrange(arr, n, j);

int x = 3 * j;
arr[x] = a;
arr[x + 1] = b;;
arr[x + 2] = c;
}


int main()
{
int n;
scanf("%d", &n);

int a[n], i;
for(i = 0; i < n; ++i)
scanf("%d", a + i);

if(n > 0 && n % 3 == 0)
arrange(a, n/3, n/3);

for(int i = 0; i < n; ++i)
printf("%d ", a[i]);
printf("\n");
}

Advertisements

16 thoughts on “In a given array of elements like [a1, a2, a3, a4, ….. an, b1, b2, b3, b4, ……. bn, c1, c2, c3, c4, …….. cn] without taking a extra memory how to merge like [a1, b1, c1, a2, b2, c2, a3, b3, c3, ………… an, bn, cn]

  1. That's not inplace. You are storing the entire array in the stack of program. This is even worse that copying the entire array into and then putting it into their right position(not inplace).

  2. Hi all,I was testing this program. The below program worked………….#include #define SIZE 12 //multiple of 3void arrange(int arr[], int n, int i){ if(i == 1) { arr[1] = arr[n]; arr[2] = arr[n << 1]; return; } int a = arr[i – 1]; int b = arr[n + i – 1]; int c = arr[2*n + i – 1]; arrange(arr, n, i – 1); int x = 3 * (i – 1); arr[x] = a; arr[x + 1] = b; arr[x + 2] = c; }int main(){ int n = SIZE; int a[SIZE], i; printf("\nEnter %d numbers", SIZE); for(i = 0; i < n; ++i) scanf("%d", a + i); if(n != 0 && n % 3 == 0)arrange(a, n/3, n/3); for(i = 0; i < n; ++i)printf("%d ", a[i]); printf("\n");}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s