162k views
4 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.

1 Answer

5 votes

Answer:

Here's a program that implements the requested selection sort in descending order with the specified guidelines:

def selection_sort_descending(numbers):

# Iterate through the list

for i in range(len(numbers) - 1):

max_index = i

# Find the index of the maximum element in the remaining unsorted part of the list

for j in range(i + 1, len(numbers)):

if numbers[j] > numbers[max_index]:

max_index = j

# Swap the maximum element with the current element

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

# Print the list after each iteration

print(numbers)

# Example usage

input_list = [20, 10, 30, 40]

selection_sort_descending(input_list)

# Another example usage

input_list2 = [7, 8, 3]

selection_sort_descending(input_list2)

Step-by-step explanation:

This program takes a list of integers and sorts it in descending order using the selection sort algorithm. It also outputs the list after each iteration of the outer loop, as requested.

User Travis Acton
by
8.5k points