Reputation:
I'm trying to create a program that orders a random list of 10 numbers from largest to smallest using the insertion sort algorithm. That is, finding the largest number in a list and using .append to add it to a new list. If this is repeated until the end of the list, then the new list will be ordered from largest to smallest. I have already created a program that successfully creates a random list, finds the largest number in the list, and adds it to a new list, the only problem is that I can't find a way to get the program to repeat 10 times. Thanks!
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
Please note that the point of this program is to not use any functions that will sort the list for me.
Upvotes: 0
Views: 3596
Reputation: 2826
You can do it by removing in each step the maximum value from the unsorted list and appending to the new one. It is not very efficient but it's fairly simple.
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))
Edit: if you want to avoid using the built-in function max()
, you can write it on your own using reduce()
.
mx = lambda x: reduce(lambda xs, ys: xs if xs > ys else ys, x)
Then just replace max
with mx
at the line which finds max_index
.
Upvotes: 0