选择排序遇到的引用和传值问题记录


1
private static void SelectionSort(){ 2 Scanner sc = new Scanner(System.in); 3 for(int i=0;i<6;i++){ 4 array[i] = sc.nextInt(); 5 } 6 int a=array.length; 7 int temp = array[0];//temp is the maximum number 8 while (a-->0){ 9 for(int j=0;j<a;j++){ 10 if(array[j]>temp){ 11 temp = array[j]; 12 } 13 } 14 int c = array[a]; 15 array[a]= temp; 16 temp=c; 17 System.out.println(array[a]); 18 System.out.println(temp+" --"); 19 for(int i=0;i<6;i++){ 20 System.out.print(array[i]+" "); 21 } 22 System.out.println(); 23 } 24 }

错误输出示例

应该是第16行,误以为temp是array[j]的引用,但实际上并没有修改array[j]的值。

还是用记录下标的方式最为稳妥。

 1 while (a-->0){
 2             for(int j=0;j<a;j++){
 3                 if(array[j]>array[temp]){
 4                     temp = j;
 5                 }
 6             }
 7             int c = array[a];
 8             array[a]= array[temp];
 9             array[temp]=c;
10         }

算法正确输出

posted @ 2019-03-01 16:10  略略略——  阅读(176)  评论(0编辑  收藏  举报