📅  最后修改于: 2020-12-10 03:51:53             🧑  作者: Mango
这是一种非常简单的方法,可以按递增或递减的顺序对数字进行排序。
说明在数组A =(4、15、7、18和16)上进行INSERTION SORT的操作。
A [] =
4 | 15 | 7 | 18 | 16 |
对于j = 2到5
J=2, key=A [2]
Key=15
I=2-1=1, i=1
While i>0 and A [1]>15
A Condition false, so no change
Now=3, key=A [3] =7
I=3-1=2
I=2, key=7
While i>0 and A [2]>key
Condition is true
So A [2+1] ← A [2]
A [3] ← A [2]
即
4 | 15 | 18 | 16 |
and i=2-1=1, i=1
while i>0 and A [1]>key
A Condition false. So no change
Then A [1+1] ← key
A [2] ← 7
那是
4 | 7 | 15 | 18 | 16 |
For j=4
Key=A [4]
Key = 18, i=3
Now, while 3>0 and A [3]>18
The Condition is false, No change.
Similarly, j=5
Key=A [5]
So key=16, i=4
Now while 4>0 and A [4]>16
Condition is true
So A [5] =16 and i=4-1=3
Now while 3>0 and A [3]>16
Condition is false
So A [3+1] =A [4] =16
排序后的数组是:
4 | 7 | 15 | 16 | 18 |