我需要编写一个程序。此方法将整数数组作为输入并返回数组,其中每个值都与其相邻元素交换。如果数组的计数为奇数,则不交换最后一个元素。
int[] array ={111,77,88,44,32,11,13,25,44}
结果:
finalarray= 77,111,44,88,11,32,25,13,44
我尝试使用嵌套的for循环,但没有得到
public static int[] swap(int array[]) {
for (int i = 1; i < array.length; i++) {
for (int j = i; j <= i; j++) {
int temp = array[i - 1];
array[i - 1] = array[j];
array[j] = temp;
}
}
for (int k = 0; k < array.length; k++) {
System.out.print(array[k] + " ");
}
//Desired output 17,111,44,88,11,32,25,13,44
return array;
}
public static void main(String args[]) {
int[] number = { 111, 17, 88, 44, 32, 11, 13, 25, 44 };
number = swap(number);
}
答案 0 :(得分:1)
您到目前为止尝试过的代码在哪里?!
反正
for (int i = 0; i < array.length; i += 2) {
if(i+1 >= array.length) {
break;
}
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
答案 1 :(得分:1)
int[] array ={111,77,88,44,32,11,13,25,44};
int[] output = new int[array.length];
for(int x = 0; x < array.length - 1; x += 2) {
output[x] = array[x + 1];
output[x+1] = array[x];
}
if(array.length % 2 != 0) {
output[output.length-1] = array[array.length-1];
}
您只需要遍历数组,并使用交换后的值填充新数组。
答案 2 :(得分:0)
这应该可以解决问题!
public static final <T> void swap (T[] a, int i, int j) {
T t = a[i];
a[i] = a[j];
a[j] = t;
}
public static final <T> void swap (List<T> l, int i, int j) {
Collections.<T>swap(l, i, j);
}
private void test() {
String [] a = {"Hello", "Goodbye"};
swap(a, 0, 1);
System.out.println("a:"+Arrays.toString(a));
List<String> l = new ArrayList<String>(Arrays.asList(a));
swap(l, 0, 1);
System.out.println("l:"+l);
}
答案 3 :(得分:-1)
首先,您有一个函数可以像这样交换两个元素:
public void swap(int [] array , int firstIndex , int secondIndex){
int temp = array[firstIndex];
array[firstIndex] = array[secondIndex];
array[secondIndex] = temp;
}
//Now it's time to navigate over the array like this:
for(int i = 0 ; i < array.length -1;i+=2){
swap(array,i,i+1);
}