简体   繁体   中英

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.

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++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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