Python: Print the output N-1 number of times showing the swapswhile doing a selection sort on a random list of numbers


I was trying to write a function called modified_selection_sort that takes a list of int values as a parameter and sorts it increasing order. The function should begin by swapping the largest element into the
last position first, then the second largest into the second-to-last position, etc.
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), and the function should have no return value.

The code that I have written so far does sort the list but I can’t get the output to be displayed in the way it should be.

Here’s what I tried:

def modified_selection_sort(A:list):
    for i in range(len(A)):
        min_idx = i
        for j in range(i+1, len(A)):
            if A[min_idx] > A[j]:
                min_idx = j
            if A[max_idx] < A[j]:
                max_idx = j               
            print(A)    #I tried to print the results here?   
        A[max_idx], A[min_idx] = A[min_idx], A[max_idx] #here's the swapping
numbers = [int(number) for number in input().split()]

Here’s what I expected:
say the input list was: [30 40 20 10]

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

But what I get is:

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

Am I missing a step somewhere? Should I try making another loop inside the j loop that prints out the output (n-1) number of times?

Asked By: degeneratematter



You don’t need min_idx. You should start from the last index of the list instead and work backwards to keep comparing items in the unsorted portion of the list with the item at max_idx:

def modified_selection_sort(A):
    for i in range(len(A) - 1, 0, -1):
        max_idx = i
        for j in range(i):
            if A[j] > A[max_idx]:
                max_idx = j
        A[i], A[max_idx] = A[max_idx], A[i]

so that:

modified_selection_sort([30, 40, 20, 10])


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


Answered By: blhsing

If you only want to see the list after the swaps, then place the print directly below the line where the swapping happens.

A[max_idx], A[min_idx] = A[min_idx], A[max_idx] #here's the swapping
print(A, min_idx, max_idx)

Besides that, there is a problem with this code’s logic, you are allowing swaps to happen always, even when they aren’t beneficial. The prints are indicating that the program is finding 40 and 10 as the max and min, then swapping them, then its finding the 40 and 10 as the max and min again, and swapping again, then repeating the process with 10 and 20

Answered By: PedroTurik
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.