[Python] insertionsort different algorithm

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    I wanted to write insertionsort algorithm in a different way but I can not understand why my code does not work properly.

    def insertionsort(x):
    i=1
    index=0
    while(i>=1 and i<len(x)): #starts from the first index
    j=i-1 #comparing starts from one index lower
    while(0<=j<i): #determines the range of j
    if(x[j]>x):
    x[j+1]=x[j]
    j=j-1 #decrements j up to -1
    else:
    index=j+1 #determines the place where i th element of the list go.
    break

    index=j+1
    x[index]=x
    i=i+1 #increments i continues with unsorted list
    return x #returns the value and print(insertionsort[1,5,8,2,7,4]) gives [1,5,8,8,8,8]

    Continue reading...

Compartilhe esta Página