Results 1 to 3 of 3
- 08-10-2011, 04:25 AM #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:
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 finishedJava 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 }.gif)
But anyway, I'd like to know how to make this work for an odd array of elements. Can somebody show me?
Cheers.
- 08-10-2011, 04:45 AM #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.
- 08-10-2011, 04:52 AM #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.
Similar Threads
-
Swapping elements of an array help please
By ikillu in forum New To JavaReplies: 11Last Post: 01-15-2012, 08:49 PM -
keep the first N elements of an array only
By aneuryzma in forum New To JavaReplies: 13Last Post: 03-27-2011, 04:03 PM -
Swapping numbers in an array
By Awt582 in forum New To JavaReplies: 3Last Post: 11-01-2010, 12:03 AM -
swapping elements of vector
By sara12345 in forum New To JavaReplies: 1Last Post: 01-07-2010, 09:45 PM -
Sorting Elements in a TreeMap
By Java Tip in forum java.langReplies: 0Last Post: 04-12-2008, 08:47 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks