Jun 10, 2009

Given an array having first n ints and next n chars. A= i1 i2 i3 ... in c1 c2 c3 ... cn Write an in-place algorithm to rearrange the elements of the a

Given an array having first n ints and next n chars.
A= i1 i2 i3 ... in c1 c2 c3 ... cn
Write an in-place algorithm to rearrange the elements of the array as:
A = i1 c1 i2 c2 ... in cn
i1 i2 i3 i4 i5 i6 i7 i8 c1 c2 c3 c4 c5 c6 c7 c8//swap i5-i8 with c1-c4
i1 i2 i3 i4 c1 c2 c3 c4 i5 i6 i7 i8 c5 c6 c7 c8//swap i3,i4 with c1,c2,swap c5,c6 with i7,i8
i1 i2 c1 c2 i3 i4 c3 c4 i5 i6 c5 c6 i7 i8 c7 c8//swap i2 with c1, swap i4 with c3 ........
i1 c1 i2 c2 i3 c3 i4 c4 i5 c5 i6 c6 i7 c7 i8 c8
so we do the swap like quick sorting, the complexity is O(nlogn)

int* foo(int A[],int min, int max)
{
if(min>=max) return;
int mid=(max-min)/2;
swap(A,mid);
foo(A,min,mid);
foo(A,mid+1,max);
return;
}

swap(int* A, int mid)
{
for(int i=0;i < mid/2;i++)
{
int temp=A[mid/2+i];
A[mid/2+i]=A[mid+i];
A[mid+i]=temp;
}
}

No comments:

Post a Comment