1
\$\begingroup\$

Can this insertion sort program be improved in any way? Please suggest something in terms of efficiency and lines of code as well.

def insort(lst):
    for i in range(len(lst)-1):
        l = i + 1
        for j in range(l, -1, -1):
            print(j)
            if j == 0:
                break
            if lst[j] < lst[j-1]:
                lst[j], lst[j-1] = lst[j-1], lst[j]
    return lst

data = input("Enter the numbers separated by spaces: ")

print(insort(list(map(int, data.split()))))
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Looks good to me. It's simple and easy to read. The only nit I might have:

l = i + 1
for j in range(l, -1, -1):

could be:

for j in range(i + 1, -1, -1):

since it doesn't look like you're using l anywhere else.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks so much! I'll keep this in mind while coding similar problems. Have a good day! \$\endgroup\$
    – Meadow
    Commented Aug 1, 2017 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.