gpt4 book ai didi

python - Python 插入排序是如何工作的?

转载 作者:太空狗 更新时间:2023-10-29 17:10:35 25 4
gpt4 key购买 nike

这是插入排序的 Python 实现,我试图遵循纸上的值,但是一旦计数变量 i 大于 len(s) 我不知道该怎么做,它如何/为什么仍然运行?

def sort_numbers(s):
for i in range(1, len(s)):
val = s[i]
j = i - 1
while (j >= 0) and (s[j] > val):
s[j+1] = s[j]
j = j - 1
s[j+1] = val

def main():
x = eval(input("Enter numbers to be sorted: "))
x = list(x)
sort_numbers(x)
print(x)

最佳答案

或者,这个:

def ins_sort(k):
for i in range(1,len(k)): #since we want to swap an item with previous one, we start from 1
j = i #create i's copy (or not)
temp = k[j] #temp will be used for comparison with previous items, and sent to the place it belongs
while j > 0 and temp < k[j-1]: #j>0 bcoz no point going till k[0] since there is no seat available on its left, for temp
k[j] = k[j-1] #Move the bigger item 1 step right to make room for temp
j=j-1 #take k[j] all the way left to the place where it has a smaller/no value to its left.
k[j] = temp
return k

关于python - Python 插入排序是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12755568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com