插入值 > 當前元素 的位置 iia[i]
main() {
int i, j, p, q, s, n;
int a[11] = {127, 3, 6, 28, 54, 68, 87, 105, 162, 18};
// 先降序排序
for (i=0; i<10; i++) {
p = i; q = a[i];
for (j=i+1; j<10; j++)
if (q < a[j]) { p = j; q = a[j]; }
if (p != i) {
s = a[i]; a[i] = a[p]; a[p] = s;
}
printf("%d ", a[i]);
}
// 插入新元素
printf("\ninput number:\n");
scanf("%d", &n);
for (i=0; i<10; i++)
if (n > a[i]) {
for (s=9; s>=i; s--) a[s+1] = a[s]; // 後移
break;
}
a[i] = n;
// 輸出結果
for (i=0; i<=10; i++) printf("%d ", a[i]);
printf("\n");
}
s=9; s>=i; s--),避免覆蓋break 跳出外層循環,i 保持插入位置break,i=10,插入末尾 a[10]輸入 47 → 插入 54 和 28 之間,輸出序列有序。
vector::insert / list 封裝此邏輯有序數組插入是數據結構基礎操作,掌握其邊界條件與移動邏輯至關重要。