使用插入排序从最大到最小排序列表

时间:2015-01-25 21:39:07

标签: python for-loop while-loop

我尝试创建一个程序,使用插入排序算法从10到最大的数字的随机列表。也就是说,找到列表中的最大数字并使用.append将其添加到新列表中。如果重复此操作直到列表结尾,则新列表将从最大到最小排序。 我已经创建了一个成功创建随机列表的程序,找到列表中最大的数字,并将其添加到新列表中,唯一的问题是我无法找到让程序重复的方法10倍。谢谢!

import random
num_list = []
new_list=[]

for num in range(10):
    num_list.append(random.randrange(0,11))

largest=num_list[0]

for repeat in range(len(num_list)):
    for large in num_list:
        if large>largest:
            largest=large
            new_list.append(largest)

print new_list

请注意,此程序的目的是不使用任何能为我排序列表的功能。

1 个答案:

答案 0 :(得分:0)

您可以通过在每个步骤中删除未排序列表中的最大值并附加到新列表来执行此操作。它效率不高但很简单。

new_list = []

# init random list
num_list = [random.randrange(0, 11) for _ in range(10)]

# while condition will evaluate to False 
# only when num_list is empty

while num_list:  
    # find index of maximum item
    max_index = num_list.index(max(num_list)) 

    # remove item with pop() and append to sorted list
    new_list.append(num_list.pop(max_index))

编辑:如果您想避免使用内置函数max(),可以使用reduce()自行编写。

mx = lambda x: reduce(lambda xs, ys: xs if xs > ys else ys, x)

然后在找到max的行中将mx替换为max_index