Sidharth Samant Sidharth Samant - 6 months ago 17
Python Question

Insertion sort in Python doesn't work

I tried this code from this question - Python insertion sort. I modified the code a bit, got rid of the

eval()
.

def sort_numbers(s):
for i in range(1, len(s)):
val = s[i]
j = i - 1
while (j >= 0) and (s[j] > val):
s[j+1] = s[j]
j = j - 1
s[j+1] = val
print s

x = raw_input("Enter numbers to be sorted: ").split()
sort_numbers(x)


It doesn't work for a few too many test cases.

In: 1001 101 20 24 2000
Out: 1001 101 20 2000 24


I've also tried with some negative numbers. The code doesn't work. Why is this so?

Answer

This is because x is a List of strings and not integers. You can correct your input example by placing this code before sort_numbers:

x = [ int(v) for v in x ]

Original result:

Enter numbers to be sorted: 1001 101 20 24 2000
['1001', '101', '20', '2000', '24']

Result after adding that line:

Enter numbers to be sorted: 1001 101 20 24 2000
[20, 24, 101, 1001, 2000]

Notice that now the List shown from print s does not have elements surrounded by quotes