Write a program in which you manually sort a list of integers from 0 to 9. You c
ID: 3536600 • Letter: W
Question
Write a program in which you manually sort a list of integers from 0 to 9. You can use the following code at the top of your program to generate and randomize the list unordered:
import random
unordered = range(10)
random.shuffle(unordered)
You can use an established method to sort the list called the selection sort. Here's the pseudocode for an implementation of the selection sort algorithm that removes elements from an original, unordered list and appends them to a new, ordered list:
Create an empty list to hold the empty elements
While there are still elements in the unordered list
Set a variable, lowest to the first element in the unordered list
For each element in the unordered list
If the element is lower than lowest
Assign the value of that element to lowest
Append lowest to to the ordered list
Remove lowest from unordered list
An important point to remember is that Python's implementation of list sorting is far more efficient than this implementation of the selection sort. So, when you want to sort a list(other than on this project), you should use the built-in sort() list method.
Explanation / Answer
import random
unordered = range(10)
ordered = []
random.shuffle(unordered)
print " printing unordered list here"
print unordered
while unordered:
min_value = unordered[0]
for i in range(1,len(unordered)-1):
if unordered[i]<min_value:
min_value = unordered[i]
ordered.append(min_value);
unordered.remove(min_value);
print "after selection sort applied, printing ordered list here"
print ordered
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.