Swapping first array element with last, second with second last and so on

十年热恋 提交于 2021-01-04 05:56:12

问题


I have an array, where I have to swap the first value with last, second with second last, and so on.

I tried doing it like in the code below, but it only works halfway, replacing the other half with zeros. Could somebody explain what is wrong here, please?

for (i = 0; i < arr.length; i++) {
    temp = arr[i];
    arr[i] = arr[arr.length - 1 - i];
    arr[arr.length - 1 - i] = temp;
}

回答1:


You have the right idea, but you're iterating over the whole array, so you switch the first and the last elements, and then back again when you reach the last one (and have the same issue for every pair of switched elements). You should stop the loop when you reach half point:

for (i = 0; i < arr.length / 2; i++) { // Here!
     temp = arr[i];
     arr[i]  = arr[arr.length - 1 - i];
     arr[arr.length - 1 - i] = temp;
}



回答2:


If you want to reverse the whole array, you can do below, but Collections classes in java can do it too. You may want to use a second array, check below example

String arr[] = {"1", "2", "3", "4", "5"};
String temparr[] = new String[arr.length];
System.out.println(Arrays.toString(arr));
for (int i = 0; i < arr.length; i++) {
    temparr[i] = arr[arr.length - i - 1];
}
System.out.println(Arrays.toString(temparr));



回答3:


Correct approach is to iterate over this array from beginning to the middle and swap elements i and length-i-1, i. e. first and last, second and second last and so on:

int[] arr = {1, 4, 6, 5, 23, 3, 2};

IntStream.range(0, arr.length / 2).forEach(i -> {
    int temp = arr[i];
    arr[i] = arr[arr.length - i - 1];
    arr[arr.length - i - 1] = temp;
});

System.out.println(Arrays.toString(arr));
// [2, 3, 23, 5, 6, 4, 1]

If you continue iterating from middle to the end, you swap them back:

IntStream.range(arr.length / 2, arr.length).forEach(i -> {
    int temp = arr[i];
    arr[i] = arr[arr.length - i - 1];
    arr[arr.length - i - 1] = temp;
});

System.out.println(Arrays.toString(arr));
// [1, 4, 6, 5, 23, 3, 2]

See also:
• Is there any other way to remove all whitespaces in a string?
• Is there a way to reverse specific arrays in a multidimensional array in java?



来源:https://stackoverflow.com/questions/65450651/swapping-first-array-element-with-last-second-with-second-last-and-so-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!