題目給出插入排序框架,需填入四處關鍵程式碼:
n[0] = n[i]; // 代碼1:備份待插入值
j > 0 && n[0] < n[j] // 代碼2:向前掃描條件(已排序區間從右向左)
n[j+1] = n[j]; // 代碼3:元素右移騰空位
n[j+1] = n[0]; // 代碼4:插入備份值
i = 1 ~ length-1,每輪處理一張新牌。n[i] 暫存至 n[0](哨兵位置)。j 從 i-1 向左掃描,只要 n[j] > n[0] 就右移。j+1 即為插入點,寫回 n[0]。public class InsertSortDemo {
public static void sort(int[] n) {
for (int i = 1; i < n.length; i++) {
n[0] = n[i];
int j = i - 1;
while (j > 0 && n[0] < n[j]) {
n[j + 1] = n[j];
j--;
}
n[j + 1] = n[0];
}
}
public static void main(String[] args) {
int[] a = {5, 2, 9, 1, 5, 6};
sort(a);
System.out.println(Arrays.toString(a)); // [1, 2, 5, 5, 6, 9]
}
}
理解「哨兵 + 右移 + 插入」三步驟,即可輕鬆應對各類填空與手寫排序考題。