Skip to content

Commit ed19d23

Browse files
committed
fix basic sort
1 parent a2fb515 commit ed19d23

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

docs/12_基本排序算法/basic_sort.md

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -94,10 +94,14 @@ def test_select_sort():
9494

9595

9696
# 插入排序
97-
这个拿小盆友举例子就不太好了,除非是叠罗汉。想象你手里有一些扑克牌,它们顺序是散乱的,现在需要你把它们整理成有序的,你会怎么做呢?
97+
插入排序很多教科书都是用扑克牌的例子讲的,想象你手里有一些扑克牌,它们顺序是散乱的,现在需要你把它们整理成有序的,你会怎么做呢?
9898
首先拿最顶上的一张,然后拿第二张,第二张点数大,你就把第二张放在第一张的下边,否则放在第一张上边。
9999
当你拿第三张的时候,你同样会找到适合它大小的位置插入进去。
100100

101+
换成小朋友一样,第一个小盆友只有一个人我们假设是有序的,然后第二个小盆友会跟第一个比,如果第一个高就交换位置。
102+
接下来第三个小盆友从第二个位置开始比较,如果没第二个高就交换位置,然后没第一个高也交换位置,保持前边三个小盆友身高有序就好。
103+
依次类推,等到最后一个小盆友也转移到合适的位置,整个队列就是有序的了。
104+
101105
插入排序就是这个道理, 每次挑选下一个元素插入已经排序的数组中,初始时已排序数组只有一个元素。我们就直接上代码吧。
102106

103107

@@ -107,14 +111,13 @@ def insertion_sort(seq):
107111
n = len(seq)
108112
print(seq)
109113
for i in range(1, n):
110-
value = seq[i] # save the value to be positioned
111-
# find the position where value fits in the ordered part of the list
114+
value = seq[i] # 保存当前位置的值,因为转移的过程中它的位置可能被覆盖
115+
# 找到这个值的合适位置,使得前边的数组有序 [0,i] 有序
112116
pos = i
113117
while pos > 0 and value < seq[pos-1]:
114-
# Shift the items to the right during the search
115-
seq[pos] = seq[pos-1]
118+
seq[pos] = seq[pos-1] # 如果前边的元素比它大,就让它一直前移
116119
pos -= 1
117-
seq[pos] = value
120+
seq[pos] = value # 找到了合适的位置赋值就好
118121
print(seq)
119122

120123

0 commit comments

Comments
 (0)