将char数组中的元素切换到int数组中的相应位置java

Switching a elements in char array to the corresponding positions in an int array java

我正在尝试将 letters 数组中的元素切换到 positions 数组中的相应位置。元素正在交换但未交换到正确的位置。我这样做是完全错误还是我的逻辑有问题?

public class Words
{
    public static void main (String args[])
    {
        char letters[] = {'l', 'o', 'e', 'h', 'l'};
        int positions[] = {2, 4, 1, 0, 3};

        int limit1 = letters.length;
        int temp1;
        char temp2;
        for(int i = 0; i < letters.length; i++)
        {
            limit1--;
            for(int j = 0; j < limit1; j++)
            {
                temp1 = positions[j];
                temp2 = letters[temp1];
                letters[temp1] = letters[j];
                letters[j] = temp2;
            }
        }
        for(int i = 0; i < letters.length; i++)
        {
            System.out.print(letters[i] + " ");
        }
    }
}

您的代码有误:

 ...
 temp2 = letters[temp1]; // temp2 is a letter now 
 ...
 letters[temp2] = letters[j]; // the index you are using is a unicode char

问题已解决,有一种更简单的方法,您可以创建一个数组并将给定位置的元素分配给它。这是一种更简单的方法,由 https://whosebug.com/users/5221149/andreas

给出的想法
public class Words
{
    public static void main (String args[])
    {
        char letters[] = {'l', 'o', 'e', 'h', 'l'};
        int positions[] = {2, 4, 1, 0, 3};

        char[] array = new char [letters.length];
        int limit1 = letters.length;
        int temp1;
        char temp2;

        for(int i = 0; i < letters.length; i++)
        {
            temp2 = letters[i];
            temp1 = positions[i];
            array[temp1] = temp2;
        }
        for(int i = 0; i < letters.length; i++)
        {
            System.out.print(array[i]);
        }
    }
}

如果您不必就地执行此操作,只需创建一个新数组就会容易得多。

char[] letters = {'l', 'o', 'e', 'h', 'l'};
int[] positions = {2, 4, 1, 0, 3};

char[] result = new char[letters.length];
for (int i = 0; i < letters.length; i++)
    result[positions[i]] = letters[i];

System.out.println(result);

输出

hello

对于就地解决方案,可以执行以下操作。与上面相同的输出。

char letters[] = {'l', 'o', 'e', 'h', 'l'};
int positions[] = {2, 4, 1, 0, 3};

for (int i = 0, j; i < letters.length; i++) {
    while ((j = positions[i]) != i) {
        char tempLetter = letters[i];
        letters[i] = letters[j];
        letters[j] = tempLetter;
        int tempPosition = positions[i];
        positions[i] = positions[j];
        positions[j] = tempPosition;
    }
}

System.out.println(letters);

只用一个循环就可以很容易地写出来。

for (int i = 0, j; i < letters.length; ) {
    if ((j = positions[i]) == i) {
        i++;
    } else {
        char tempLetter = letters[i];
        letters[i] = letters[j];
        letters[j] = tempLetter;
        int tempPosition = positions[i];
        positions[i] = positions[j];
        positions[j] = tempPosition;
    }
}