简体   繁体   中英

Python descending selection sort

I am trying to submit an assignment for school. They are using this irritating website that only accepts program output in a very specific format. It's just a selection sort in descending order, but they want to see each step in the sorting printing out. The algorithm works, but it is taking a lot of steps to sort. I'm not sure what I can change to make it more efficient, or if it's where I have placed the print statements. Any help would be appreciated.

 array = [20,10,30,40]
    
    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)

Output:

[20, 10, 30, 40]
[30, 10, 20, 40]
[40, 10, 20, 30]
[40, 20, 10, 30]
[40, 30, 10, 20]
[40, 30, 20, 10]

Expected output:
40 10 30 20 
40 30 10 20 
40 30 20 10 

The swap should not be inside your inner loop. You need to let the whole inner loop finish to find the correct value for max_index .

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]

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