简体   繁体   中英

Descending selection sort with output during execution outputs the list unchanged

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).

This is what I have, but the output is just printing the input twice exactly the way it is entered. What am I doing wrong here?

array = []
array.append(str(input(" ")))
    
for i in range(len(array)):
    max_index = i
    for j in range(i+1, len(array)):
        if array[j] > array[max_index]:
            max_index = j
    print(array)
    array[i],array[max_index] = array[max_index],array[i]
    
    print(array)

Input:

0 10 20 30 40

Output:

['0 10 20 30 40']
['0 10 20 30 40']

Based on your question

What am I doing wrong here?

I'm going to take this line as a point of reference:

array.append(str(input(" ")))
>>> 0 10 20 30 40
print(array)
>>> ['0 10 20 30 40']

As you can see the output is of length 1. It only has one item which is a String. You basically append the user input as a single string. Because you don't split the items in the input.

Solution

Input

 0 10 20 30 40 50

To do exactly what you wanted to do I'd do this. I just split the string based on your input in the question.

array = []
array=input(" ").split(" ")

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

    print(array)

Output

['50', '10', '20', '30', '40', '0']
['50', '40', '20', '30', '10', '0']
['50', '40', '30', '20', '10', '0']
['50', '40', '30', '20', '10', '0']
['50', '40', '30', '20', '10', '0']
['50', '40', '30', '20', '10', '0']

If you want your output to be a list of integers. Here, I split the string and changed the type of item to int when switching the pair. Also when doing comparison, I changed the type of the item to int

array = []
array=input(" ").split(" ")

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

    print(array)

Output

[50, '10', '20', '30', '40', 0]
[50, 40, '20', '30', 10, 0]
[50, 40, 30, 20, 10, 0]
[50, 40, 30, 20, 10, 0]
[50, 40, 30, 20, 10, 0]
[50, 40, 30, 20, 10, 0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM