Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
insertion sort
#1
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)
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,328 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  Amortized analysis: Insertion in a list quazirfan 1 1,350 Sep-27-2021, 02:06 AM
Last Post: deanhystad
  Insertion sort algorithm courtesy of YouTuber Joe James Drone4four 3 2,204 Dec-07-2020, 02:11 PM
Last Post: perfringo
  Detecting USB Device Insertion on Windows 10 Atalanttore 0 2,401 Jan-17-2020, 02:46 PM
Last Post: Atalanttore
  Tree insertion and variable referencing hshivaraj 3 3,335 Dec-10-2017, 04:29 PM
Last Post: Windspar

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020