Results 1 to 3 of 3
  1. #1
    kumalh is offline Member
    Join Date
    Jul 2011
    Posts
    16
    Rep Power
    0

    Default 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. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,759
    Rep Power
    7

    Default

    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. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,759
    Rep Power
    7

    Default

    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

  1. Swapping elements of an array help please
    By ikillu in forum New To Java
    Replies: 11
    Last Post: 01-15-2012, 08:49 PM
  2. keep the first N elements of an array only
    By aneuryzma in forum New To Java
    Replies: 13
    Last Post: 03-27-2011, 04:03 PM
  3. Swapping numbers in an array
    By Awt582 in forum New To Java
    Replies: 3
    Last Post: 11-01-2010, 12:03 AM
  4. swapping elements of vector
    By sara12345 in forum New To Java
    Replies: 1
    Last Post: 01-07-2010, 09:45 PM
  5. Sorting Elements in a TreeMap
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-12-2008, 08:47 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •