在写冒泡的时候遇到了一个问题,就是值传递问题,我写的是swap函数,本来只传两个数值是不可以的例如swap(int a,int b)这样只是单纯的值传递,并不能起到交换两个数值的作用,所以要直接对数组进行操作才是王道。想起C++中其实是按指针给值,直接修改堆里的值,而java里没有指针,所以要将“引用”传进来,我不知道用引用合不合适,但是这个引用和C++中的引用是有很大区别的,我觉得反而有点类似于指针。
public class BubbleSort { public static void swap(int[] args,int index1,int index2) { int temp = 0 ; temp= args[index1]; args[index1] = args[index2]; args[index2] = temp; } public static void bubblesort(int[] num){ for(int i=0;i<num.length;i++){ for(int j=0;j<num.length-i-1;j++){ if(num[j]>num[j+1]){ swap(num,j,j+1); } } } } public static void main(String[] args){ int[] num={1,2,6,8,4,3}; bubblesort(num); for(int a:num){ System.out.println(a); } // int[] a={1,2}; // swap(a,0,1); // System.out.println("a:"+a[0]); // System.out.println("b:"+a[1]); } }