asked 202k views
2 votes
Write a program that takes an integer list as input and sorts the list into descending order using selection sort. The program should use nested loops and output the list after each iteration of the outer loop, thus outputting the list N-1 times (where N is the size of the list).

Important Coding Guidelines:

Use comments, and whitespaces around operators and assignments.
Use line breaks and indent your code.
Use naming conventions for variables, functions, methods, and more. This makes it easier to understand the code.
Write simple code and do not over complicate the logic. Code exhibits simplicity when it’s well organized, logically minimal, and easily readable.
Ex: If the input is:

20 10 30 40
the output is:

[40, 10, 30, 20]
[40, 30, 10, 20]
[40, 30, 20, 10]
Ex: If the input is:

7 8 3
the output is:

[8, 7, 3]
[8, 7, 3]
Note: Use print(numbers) to output the list numbers and achieve the format shown in the example.
my code:
def descending_selection_sort(numbers):

# loop through all numbers in the list

for i in range(len(numbers)):
max_index = i

for j in range(i+1, len(numbers)):
if numbers[j] > numbers[max_index]:
max_index = j

numbers[i], numbers[max_index] = numbers[max_index], numbers[i]


print(numbers)


Program errors displayed here
Traceback (most recent call last):
File "main.py", line 14, in
numbers[i], numbers[max_index] = numbers[max_index], numbers[i]
NameError: name 'numbers' is not defined

1 Answer

5 votes

Answer:

def selection_sort(numbers):

n = len(numbers)

for i in range(n - 1):

max_index = i

for j in range(i + 1, n):

if numbers[j] > numbers[max_index]:

max_index = j

numbers[i], numbers[max_index] = numbers[max_index], numbers[i]

print(numbers)

numbers = list(map(int, input("Enter a list of integers separated by space: ").split()))

selection_sort(numbers)

Step-by-step explanation:

answered
User Mkostya
by
8.6k points