java交换两个数的数值

来源:互联网 发布:未登录uc淘宝手机助手 编辑:程序博客网 时间:2024/06/04 18:37
开始学习算法,遇到两个数的交换问题的时候,出现了一些问题,我各种都交换不了。
是的。我就是想写个全排列
void Perm(int[] array,int start,int end){
if(start == end){        //只有一个元素需要排序
for(int i=0;i<=end;i++){
System.out.print(array[i] +" ");
}
System.out.println() ;
}else{     //还有多余的数
for(int i=0;i<=end;i++){
Num num = new Num(array[start],array[i]) ;
Swap(num) ;        //交换两个数
Perm(array,start+1,end) ;
Swap(num) ;        // 交换回来
}
}
}
由于java传递数据的时候是数值传递的
我的第一种方法: ========================
//交换数据
public static void Swap(int a,int b){
int temp  ;
temp = a ;
a = b ;
b = a ;
}


然后我包装成了类===================
class Num{
public int a,b ;
public Num(int a,int b){
this.a = a ;
this.b = b ;
}
}
public static void Swap(Num p){
int temp ;
temp = p.a ;
p.a = p.b ;
p.b = temp ;
}
Num num = new Num(array[start],array[i]) ;
Swap(num) ;




发现还是交换不了,我开始有些慌乱,到底什么问题,于是我又换方法,




static void Swap(int[] a){
int temp ;
temp = a[0] ;
a[0] = a[1];
a[1] = temp ;
}


果然还是需要用到数组的。
0 0
原创粉丝点击