简体   繁体   English

交换数组中的相应元素

[英]Swapping corresponding elements in an Array

How would I switch corresponding elements in an array (Ex: First with last, Second with one before last) using a loop. 我如何使用循环切换数组中的相应元素(例如:第一个倒数第二个,第二个倒数第二个)。 I've worked out the code using a loop, but it doesn't give the desired result in Eclipse. 我已经使用循环编制了代码,但是在Eclipse中却没有得到期望的结果。

int[] a = {1, 2, 3, 4, 5};
int k = 0;
int temp = 0;
while(k < a.length)
{
  temp = a[k];
  a[k] = a[a.length - 1 - k];
  a[a.length - 1 - k] = temp;
  k++;
}

Assume that you don't know the values in the array or how long it is. 假设您不知道数组中的值或数组的长度。

您只应在数组中途循环,即while (k < a.length / 2) -如果继续超出该范围,最终将被交换的元素交换回其原始位置。

easier way 
for(int i=0,j=a.length-1;i<j;i++,j--)
{
  int temp=a[i];
  a[i]=a[j];
  a[j]=temp;
}

You're iterating over the entire array, which means you end up undoing what you did in the first half of the iteration. 您正在遍历整个数组,这意味着您最终将撤消在迭代的前半部分中所做的操作。 Just iterate for half the length of the array (round down). 只需迭代数组长度的一半(向下取整)。 This should work: 这应该工作:

int[] a = {1, 2, 3, 4, 5};
int k = 0;
int temp = 0;
while(k < (a.length / 2)) {
temp = a[k];
a[k] = a[a.length - 1 - k];
a[a.length - 1 - k] = temp;
k++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM