我的老师最近编写了一个关于如何对带有数字的列表进行排序的程序,我主要不了解布尔值语句,然后是循环中对数字进行排序的逻辑,因此在解释他所做的事情时将不胜感激。我有功课要做,排序是其中的一部分,所以我只是想理解他所做的这个例子。谢谢
d = [8, 14, 3, 5, 2, 23] # lists
size = len( d ) # size = number of elements in list
unsorted = True # what does this really mean and do?
while unsorted : # bassicly while true, but while what is true? what would make it false?
unsorted = False #? did he just change the variable to false? if so, why, and
# how is the "while unsorted" before statement still being met
i = 0 # this bassiclly begins the indency number in the list below
while i < size-1 : # so while the indency number is less than the list
# element size it will loop through the rest
if d[i] > d[i+1] : # if the number in d[i]is greater than the number after
temp = d[i] # then variable temp gets assigned that number in d[i]
d[i] = d[i+1] # this confuses me. whats the purpose of setting d[i] to d[i+1]?
d[i+1] = temp # i think this has to do with the statement above, what does it
unsorted = True # why is this suddenly turned back to true?
i += 1 # adds 1 to to indency or i until it reaches the list size to stop loop
print d
输出最终成为下面的排序列表
[2、3、5、8、14、23]
谢谢