Hunter
Hunter

Reputation: 1391

How to swap array of characters (in-place) in Java

So basically without being able / permitted to make a new array. An not being able to returning anything but actually changing and manipulating the current array. How do you take an array of characters and simply flip / reverse them.

Starting array: ['P','e','r','f','e','c','t',' ','M','a','k','e','s',' ','P','r','a','c','t','i','c','e']

Reverse back each word separate by space

Reversed: ['P','r','a','c','t','i','c','e',' ','M','a','k','e','s',' ','P','e','r','f','e','c','t'] 

This is what I have so far

Code:

  class Main {
     public static void main(String[] args) {
       char[] charArr = new char[] {'P','e','r','f','e','c','t',' ','M','a','k','e','s',' ','P','r','a','c','t','i','c','e'};
       reverseCharArray(charArr);
     }


     public static void reverseCharArray() {
       int arrLength = charArr.length;
       for (int i = 0; i <= arrLength / 2; i++) {
         charArr[arrLength - i - 1] = charArr[i];
         System.out.println(charArr);
       }
     }
   }

Update: Ok what I have found is that. What I need to do is actually swap the words the sentence of characters spell. So that the sentence is backwards / reversed.

Note: This was attempted in a online interview here: enter link description here

Upvotes: 1

Views: 2273

Answers (4)

Ravi
Ravi

Reputation: 1360

There is an algorithm for this, is as follows,

  1. Initially, reverse the individual words of the given string one by one, for the provided example "Perfect Makes Practice", after reversing individual words the string should be “tcefreP sekaM ecitcarP”.
  2. Reverse the whole string from start to end to get the desired output "Practice Makes Perfect" in the above example.

For more check Reverse words in a given string.

Upvotes: 0

Ewan Arends
Ewan Arends

Reputation: 41

Let's say you have the following array; [h, e, y, , y, o, u] you'd have to work in a pattern; from the outside to the inside (or the other way around). so, [1,2,3,4,3,2,1] you'd have to swap 1 and 1, 2 and 2 and so on. as you can see, this array has a length of 7, in this case the amount of swaps needed is exactly 4 (4 is swapped with itsself). To calculate the amount of swaps, you can simply ceil the array length divided by 2.0f.

Now you have to loop trough the array, swapping those indexes. To calculate which index to swap, you have to check at wich swap your are. Let's say you're at the second swap, the indexes of 2 in the array are 1 and 5, those of 3 are 2 and 4. You've probably recognized the pattern by now. The first index is always the amount of done swaps, where the second is the length of the array minus 1 minus the amount of done swaps.

here's this put into code;


    public static void swap(char[] array){
        int totalSwaps = (int) Math.ceil(array.length / 2.0f);
        for(int currentSwaps = 0; currentSwaps < totalSwaps; currentSwaps++){
            char char1 = array[currentSwaps];
            int position2 = array.length - (currentSwaps + 1);
            array[currentSwaps] = array[position2];
            array[position2] = char1;
        }
        System.out.println(Arrays.toString(array));
    }

EDIT: I just saw that you were asking to reverse each word in a char[], you might want to clarify that in the first sentences

to do this; I'd recommend you use String::split to split the string into a string[] and use String::toCharArray to change it to a character array. Though this does create new arrays

Upvotes: 1

Hugh Natt
Hugh Natt

Reputation: 171

This is definitely not a good solution, but it's a working one.

class Main {

public static void main(String[] args) {
    char[] charArr = new char[] { 'P', 'e', 'r', 'f', 'e', 'c', 't', ' ', 'M', 'a', 'k', 'e', 's', ' ', 'P', 'r',
            'a', 'c', 't', 'i', 'c', 'e' };
    System.out.println(charArr);
    reverseCharArray(charArr,0);
    System.out.println(charArr);
}


public static void reverseCharArray(char[] charArr, int sorted) {


    /* Look for last space*/
    int lastSpace = -1;
    for (int i = 0; i < charArr.length; i++) { 
        if (charArr[i] == ' ') {
            lastSpace = i; 
        }
    }

    /* Grab the word and move it at the beginning of the sorted array */
    for (int i = lastSpace + 1; i < charArr.length; i++) {

        int k = i;

        while (k != sorted) {
            char tmp = charArr[k-1];
            charArr[k-1] = charArr[k];
            charArr[k] = tmp;
            k--;
        }

        sorted++;
    }


    /* At this point, the last character is a space*/
    /* Else, we've swapped all the words */
    int k = charArr.length - 1;
    if (charArr[k] != ' ') {
        return;
    }

    /* If it's a space, grab it and move it at the beginning*/
    while (k != sorted) {
        char tmp = charArr[k-1];
        charArr[k-1] = charArr[k];
        charArr[k] = tmp;
        k--;
    }
    sorted++;


    /*Recursive call on the not sorted array*/
    reverseCharArray(charArr,sorted);

}}

Upvotes: 4

Ivan Kukic
Ivan Kukic

Reputation: 425

The method below swaps intervals. Note that they must be of same length.

public static char[] swap(char[] arr, int lstart, int rstart, int len){
      for(int i=lstart; i<lstart+len; i++){
        char temp = arr[i];
        arr[i] = arr[rstart+i];
        arr[rstart+i] = temp;
   }
   return arr;
}

Upvotes: 1

Related Questions