# Thread: Swapping/Sorting elements in an Array

1. Member
Join Date
Jul 2011
Posts
16
Rep Power
0

## Swapping/Sorting elements in an Array

Hello! Ok, so first off, I'm not asking for any help on an assignment or anything here. I'm just asking out of curiosity...

So I just had a Java Exam, and one of the questions asked us to write a method that sorts an array the following way:

So given an array: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The output would be: {6, 7, 8, 9, 10, 1, 2, 3, 4, 5}

I figured that out by doing this:

Java Code:
```    public static int [] arraySwap(int [] a) {
int pos = 0;
int mid = a.length / 2;

for(pos = 0; pos < mid; pos = pos + 1) {
int temp = a[pos];
a[pos] = a[mid + pos];
a[mid + pos] = temp;

}
return a
}```
However, I could only get it to work to an array with an even number of elements, not odd. So I ended up submitting the question half finished

But anyway, I'd like to know how to make this work for an odd array of elements. Can somebody show me?

Cheers.

2. One possible solution would be to copy the elements into a new array. This would require 2 loops or 2 calls to System.arraycopy.

3. Another solution would be to "rotate" the array. Store the first element in temp, Then copy all other elements down one position. Then copy the temp into the last element. Repeat this as many times as needed. For example:
1 2 3 4 5
2 3 4 5 1
3 4 5 1 2*
4 5 1 2 3*

*Depending upon which final solution is required.