Python Forum

Full Version: insertion sort
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
how to sort an array without using sort function?
I have the code please tell me what is the error in this code
x = []
n = input("enter length")
for i in range(int(n)):
    k = input("enter value")
    x.append(k)
print(x)
for j in range(1,len(x)):
    k=x[j]
    i=j-1
    while (i>0 and x[i]>k):
        x[i+1]=x[i]
        i=i-1

    x[i+1]=k
      
print(x)
k = input("enter value") gets a string. Are you expecting your sort routine to sort strings or numbers? For strings, '2' > '10'. Also remember that python list indices start at zero, so you might want to look at the range checking in your while statement.