选择排序
利用选择排序将下列数组升序排列 38,17,16,16,7,31,39,32,2,11
1 int[] ar = new int[]{38,17,16,16,7,31,39,32,2,11}; 2 for(int i=0 ;i<ar.length-1; i++){ 3 int min = i; 4 int temp = 0; 5 for(int j=i+1; j<ar.length; j++) { 6 if(ar[min] > ar[j]){ 7 min = j; 8 } 9 } 10 if( min != i){ 11 temp = ar[i]; 12 ar[i] = ar[min]; 13 ar[min] = temp; 14 } 15 System.out.println(ar[i]); 16 }
选择排序详解
选择排序就是 找出比自己小的数,然后换位置,与冒泡不同的是,冒泡是相邻的比较,选择排序是查找最小的
int [] ar = {38,17,16,16,7,31,39,32,2,11}
----------------------------------------------------
38,17,16,16,7,31,39,32,2,11
2,17,16,16,7,31,39,32,38,11
2,17,16,16,7,31,39,32,38,11
2,7,16,16,17,31,39,32,38,11
2,7,16,16,17,31,39,32,38,11
2,7,11,16,17,31,39,32,38,16
2,7,11,16,17,31,39,32,38,16
2,7,11,16,16,31,39,32,38,17
2,7,11,16,16,31,39,32,38,17
2,7,11,16,16,17,39,32,38,31
2,7,11,16,16,17,39,32,38,31
2,7,11,16,16,17,31,32,38,39
每次在 找出比自己小的值 中 找出最小的,与自己换位置