user2922148
user2922148

Reputation: 1

Reordering the values of arrays in an int array

I want to make an array from something like this:

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}

To this:

{6, 5, 4, 3, 2, 1, 0, 13, 12, 11, 10, 9, 8, 7, 20, 19, 18, 17, 16, 15, 14}

But I'm clueless how. I think this method can serve as a good alternative to the code I plan to do. (I'm using Dr. Java so no imported files BTW)

for an integer array called integer[]:

    (for j = 0; j < 3; j++) {
            (for k = 0; k = 6; k++) {
                int newj = j+1;
                int array = integer[k*newj];
                integer [k*newj] = integer[6 - k*newj -1];
                integer[6 - k*newj - 1] = array;
            }
     }

But this doesn't work.

Any advice? It's not part of an assignment, but it's part of an exam that will happen within a week and I want to be sure of this.

Upvotes: 0

Views: 172

Answers (1)

Mengjun
Mengjun

Reputation: 3197

There are 21 elements in your array. From the description you mentioned, you want to seperate it into 3 parts. Each part has 7 elements and reverse them.

For the each part, we can do the swap data opearation.

  1. Swap the 1st element with the 7th element.
  2. Sawp the 2nd element with the 6th elememt.
  3. Swap the 3rd element with the 5th element. ... ...

Note: The end condition is 7/2 for data swap. It is the middle index of the 7 elements.

Here one more thing is to determine what is the start index and end index for each divided part.

Thefollowing code is working for your requirement. Hope this can help you some.

    for (int j = 0; j <3; j++) {
        for (int k = 0; k <7/2; k++) {
            int newj = j+1;
            int array = integer[7*newj-k-1];
            integer[7*newj-k-1]= integer [7*j+k];
            integer [7*j+k] = array;
        }
    }

Upvotes: 1

Related Questions