Search code examples
python-3.xselection-sort

Tracing sorting algorithms


I am trying to trace the changes in selection sort algorithm with python, Here's a piece of my code and what I've tried, the problem I am facing is printing the results in a table-like format

l = [2,5,1,7,9,5,3,0,-1]
iterat = 1
print('Iteration' + '\t\t\t' + 'Results')
for i in range(1, len(l)):
    val_to_sort = l[i]
    while l[i-1] > val_to_sort and i > 0:
        l[i-1], l[i] = l[i], l[i-1]
        i -= 1
        print(iterat, '\t\t\t', l[0:iterat + 1],'|',l[iterat:])
        iten += 1

from the code above, I am obtaining the following results:

enter image description here

But I am trying to obtain such results

results I am trying to obtain


Solution

    • Unident print one level to the left, so it is inside the for block instead of the while block.

    • Use join and map to print the lists as a string

    • You can use enumerate instead of manually incrementing iterat


    def format_list(l):
        return ' '.join(map(str, l))
    
    l = [2,5,1,7,9,5,3,0,-1]
    print('Iteration' + '\t\t\t' + 'Results')
    
    for iterat, i in enumerate(range(1, len(l)), 1):
        val_to_sort = l[i]
        while l[i-1] > val_to_sort and i > 0:
            l[i-1], l[i] = l[i], l[i-1]
            i -= 1
        print(iterat, '\t\t\t', format_list(l[0:iterat + 1]),'|', format_list(l[iterat:]))
    

    Outputs

    Iteration           Results
    1            2 5 | 5 1 7 9 5 3 0 -1
    2            1 2 5 | 5 7 9 5 3 0 -1
    3            1 2 5 7 | 7 9 5 3 0 -1
    4            1 2 5 7 9 | 9 5 3 0 -1
    5            1 2 5 5 7 9 | 9 3 0 -1
    6            1 2 3 5 5 7 9 | 9 0 -1
    7            0 1 2 3 5 5 7 9 | 9 -1
    8            -1 0 1 2 3 5 5 7 9 | 9
    

    I can't help you with the Cyrillic text though ;)