[英]Swapping first array element with last, second with second last and so on
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;
}
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;
}
If you want to reverse the whole array, you can do below, but Collections classes in java can do it too.如果你想反转整个数组,你可以在下面做,但是 java 中的 Collections 类也可以做到。 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));
Correct approach is to iterate over this array from beginning to the middle and swap elements i
and length-i-1
, ie first and last, second and second last and so on:正确的方法是从开始到中间迭代这个数组并交换元素i
和length-i-1
,即第一个和最后一个,第二个和第二个倒数等等:
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? •有没有办法在java 的多维数组中反转特定的arrays?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.