public class HomeWork05 {<br> public static void main(String[] args) {<br> int[] array = {1, 3, 6, 8, 7, 9, 4, 10};<br> int[] ints1 = changPosition(10, 3, array);<br> for (int i = 0; i < ints1.length; i++) {<br> System.out.print(ints1[i]+"\t");<br> }<br> System.out.println("---------------------------------------");<br> int[] ints = changSpace(9, 10, array);<br> // int[] ints = changPosition(3, 7, array);<br> for (int i = 0; i < ints.length; i++) {<br> System.out.print(ints[i] + "\t");<br> }<br> <br> <br> }<br> <br> public static int[] changPosition(int n1, int n2, int[] array) {<br> int a = -1;<br> int b = -1;<br> for (int i = 0; i < array.length; i++) {<br> if (array[i] == n1) {<br> a = i;<br> }<br> }<br> for (int i = 0; i < array.length; i++) {<br> if (array[i] == n2) {<br> b = i;<br> }<br> }<br> //两个元素交换位置<br> <br> if (a > b) {//判断第一个参数下标是否大于第二个参数下标<br> System.arraycopy(array, b, array, b + 1, a - b);//是的话用第二个参数下标作为起始位置<br> // array[a] = n2;<br> array[b + 1] = n1;<br> <br> } else if (a < b) {//判断第一个参数下标是否大于第二个参数下标<br> System.arraycopy(array, a + 1, array, a, b - a);//不大于就用第一个参数下标做起始位置<br> array[b] = n1;<br> }<br> return array;<br> <br> }<br> <br> public static int[] changSpace(int n1, int n2, int[] array) {<br> int a = -1;<br> int b = -1;<br> for (int i = 0; i < array.length; i++) {<br> if (array[i] == n1) {<br> a = i;<br> }<br> }<br> for (int i = 0; i < array.length; i++) {<br> if (array[i] == n2) {<br> b = i;<br> }<br> }<br> //两个元素交换位置<br> if (a > b) {//判断第一个参数下标是否大于第二个参数下标<br> System.arraycopy(array, b, array, b, a - b);//是的话用第二个参数下标作为起始位置<br> array[a] = n2;<br> array[b] = n1;<br> <br> } else if (a < b) {//判断第一个参数下标是否大于第二个参数下标<br> System.arraycopy(array, a + 1, array, a, b - a - 1);//不大于就用第一个参数下标做起始位置<br> array[b] = n1;<br> array[a] = n2;<br> }<br> return array;<br> }<br> }