直接插入排序
public static int[] insertSort(int[] array) {
for (int i = 1; i < array.length; i++) {
int temp = array[i];
for (int j = i - 1; j >= 0 && temp < array[j]; j--) {//temp之前的值挨個比較,互換
array[j + 1] = array[j];
array[j] = temp;
}
}
return array;
}
- 結果
3421互換一次
3241互換一次
2341互換一次
2314互換一次
2134互換一次
1234互換一次 - 外循環表現出來的就是插入到一個位置
- 內循環就是用當前的temp值跟前面的數字挨個比較,符合條件進行互換。
簡單選擇排序 :
-
在要排序的一組數中,選出最小的一個數與第一個位置的數交換;
然后在剩下的數當中再找最小的與第二個位置的數交換,如此循環到倒數第二個數和最后一
個數比較為止。public static int[] insertSort(int[] array) {
int i=0;
int position;//最小值的位置
for (;i<array.length;i++){
int temp=array[i];
position=i;
int j=i+1;
for (;j<array.length;j++){
if (array[j]<temp){
temp=array[j];
position=j;
}
}
array[position]=array[i];
array[i]=temp;
}return array;
}
比如 4,3,2,1; // i=0;在i后面找到一個最小值,確定位置和數值,然后跟i位置交換。
1,3,2,4;
1,2,3,4