Array Manipulation - PLEASE HELP!

Hi I have an array containing 16 elements, but i need to rearrange them in the array.

This is the current order of the elements:

(ascending order)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

but i need to rearrange the elements into this order:

1 2 5 6 3 4 7 8 9 10 13 14 11 12 15 16

The array is of type double[ ], and called pixelArray (it's to do with image processing)

I guess I need to use 'for' loops or something, but I've been working on it for a while and am completely stuck. Please help.

Many thanks,

Peter.

[581 byte] By [usImagea] at [2007-9-29 20:26:17]
# 1

I found the logic to re-arrange the array is rather weird.. If the rule is same, and there are always 16 elements, the fastest way would be hardcoding the swap, such as:

public void swap(int[] x, int pos1, int pos2) {

int t=x[pos1];

x[pos1] = x[pos2];

x[pos2] = t;

}

....

int x[] = .... your array is here ...

swap(x, 2, 4); // swap element #2 with #4

swap(x, 3, 5); // swap element #3 with #5

... and more swaps ...

lexzeusa at 2007-7-16 0:38:13 > top of Java-index,Other Topics,Algorithms...
# 2
Thank you for your help.I'll give it a go.Peter.
usImagea at 2007-7-16 0:38:13 > top of Java-index,Other Topics,Algorithms...
# 3

> I found the logic to re-arrange the array is rather weird..

To sensible human beings this rearrangement seems weird indeed, but to idiots like me, this stuff

makes sense. The 'image processing' phrase gave me the clue. Lefs rearrange this array as a

two dimensional array. In the picture below, I've subtracted one from each element value and

represented them in hexadecimal -- original:rearrangement:

0 1 2 30 1 4 5

4 5 6 72 3 6 7

8 9 a b8 9 c d

c d e fa b e f

If you traverse this rearranged array (from value 'i' to value 'i+1') you can see the following pattern --

//

//

/__ /__

//

//

/__ /__

while the four 'Z' shaped sub-patterns are built up in a 'Z' like manner also. This 'fractal' like behaviour

is typical for two dimensional Gray codes. Traversion square tiles like this minimizes the sum of all

the 'hops' between tiles (unlike a 'normal' left-to-right, top-to-bottom traversal).

If you pay attention again to the numerical values and write them out in binary -- 0000 0001 0100 0101

0010 0011 0101 0111

1000 1001 1100 1101

1010 1011 1110 1111

after some staring and fiddling you'll notice that just bits 1 and 2 are interchanged. The following

little loop fills the original array with those values (and added one again for convenience) --

int[] a= new a[16];

for (int i= 0; i < a.length; ++i)

a[i]= (i&0x09)|// bits 0 and 3 stay in place

((i&0x04)>>1)|// move bit 2 to the right

((i&0x02)<<1)// move bit 3 to the left

+1;

kind regards,

Jos

JosHorsmeiera at 2007-7-16 0:38:13 > top of Java-index,Other Topics,Algorithms...
# 4
Thank you so much for your time and help. Pete.
usImagea at 2007-7-16 0:38:13 > top of Java-index,Other Topics,Algorithms...