JAVA实现swap

来源:互联网 发布:unity3d ngui 实例 编辑:程序博客网 时间:2024/06/10 15:21
public class Swap {public static void swap(int[] data, int a, int b) {int t = data[a];data[a] = data[b];data[b] = t;}public static void main(String[] args) {int[] data = new int[10];for (int i = 0; i < 10; i++) {data[i] = (int) (Math.random() * 100);System.out.print(" " + data[i]);}System.out.println();for (int i = 0; i < 9; i++) {for (int j = i; j < 10; j++) {if (data[i] > data[j]) {swap(data, i, j);}}}for (int i = 0; i < 10; i++) {System.out.print(" " + data[i]);}System.out.println();}}

利用数组实现,这一点上比c/c++弱爆了

或者使用org.omg.CORBA.*Holder

import org.omg.CORBA.IntHolder;/** * Created by N3verL4nd on 2016/11/21. */public class HelloWorld {    public static void swap(IntHolder x, IntHolder y){        int temp = x.value;        x.value = y.value;        y.value = temp;    }    public static void main(String[] args) {        IntHolder x = new IntHolder(10);        IntHolder y = new IntHolder(20);        System.out.println("交换前:x = " + x.value + " y = " + y.value);        swap(x, y);        System.out.println("交换后:x = " + x.value + " y = " + y.value);    }}


原创粉丝点击