有人可以向我解释为什么插入排序的方法有误吗?
def insertion_sort(m):
n = 1
while n < len(m)-1:
current_value = m[n]
if m[n] < m[n-1]:
m[n] = m[n-1]
m[n-1] = current_value
n = n + 1
return m
#how my code turned out:
m = [7,4,5] returned [4,7,5] instead of [4,5,7]
答案 0 :(得分:2)
参见代码注释中的解释:
def insertion_sort(m):
n = 1
while n < len(m): # <-- end at the end of the list
current_value = m[n]
if m[n] < m[n-1]:
m[n] = m[n-1]
m[n-1] = current_value
n = n + 1
return m
答案 1 :(得分:0)
正如alfasin所提到的,问题在于while循环条件!
您可以在此方案中实际使用for循环。看看this
为了更加pythonic,您可以将两个数字换成a,b = b,a
,如@ TigerhawkT3的评论所述!
def insertion_sort(m):
for n in range(len(m)): #iterate from 0 to m-1. auto increment value is by default 1
if m[n] < m[n-1]: m[n], m[n-1] = m[n-1], m[n]
return m
print insertion_sort([7,4,5]) 返回米 print insertion_sort([7,4,5])
输出:
[4, 5, 7]
此外,您尝试的那个实际上并不是insertion sort算法。你必须使用超过3个元素来调整你的名单!
答案 2 :(得分:0)
评论中的说明
def insertion_sort(array):
# For each number in the list (not starting
# with the first element because the first
# element has no prior (i.e., no array[j-1])
for i in range(1, len(array)):
# Set a temp variable j (totally not necessary
# but is helpful for the sake of a visual)
j = i
# While j is greater than 0 (position 0 is the
# very beginning of the array) AND the current
# element array[j] is less than the prior element
# array[j-1]
while j>0 and array[j] < array[j-1]:
# Set the current element equal to the prior
# element, and set the prior element equal to
# the current element (i.e., switch their positions)
array[j], array[j-1] = array[j-1], array[j]
# Decrement j (because we are moving each element
# towards the beginning of the list until it is
# in a sorted position)
j-=1
return array
array = [1, 5, 8, 3, 9, 2]
首次for循环迭代:[1,5,8,3,9,2]
(5
已经处于排序位置)
第二个for循环迭代:[1,5,8,3,9,2]
(8
已经处于排序位置)
第三:[1,3,5,8,9,2]
(将3
移回,直至其排序)
第四:[1,2,3,8,9]
(移动2
,直到它排序)
希望这个小小的插图有所帮助。