1

My code---->

A = [17, 15, 5, 20, 99, 100]

left = []
right = []
left.append(A[ : len(A)/2   ])
#right.append(A[ len(A)/2  : ])

print("Left Before Sort : {l}".format(l=left))

for j in range(1, len(left)):
        key = left[j]
        i = j - 1
        while (i >= 0 and left[i] > key):
            left[i+1] = left[i]
            i -= 1
        left[i+1] = key




print("Left After Sort {l}".format(l=left))

Why left ain't got sorted? I tried different namings also...but same output.

Uri Goren
  • 13,386
  • 6
  • 58
  • 110
Raj Juja
  • 13
  • 2
  • 3
    Use `left.extend` instead. The problem is appending a list makes that list a single element inside the bigger list. It does not extend it, so to speak. – cs95 Aug 06 '17 at 17:54
  • `len(left) == 1`. `.append(A[ : len(A)/2 ]))` appends a single list to `left`consisting of the first half of `A`. You probably wanted `extend()` – dhke Aug 06 '17 at 17:54
  • Either extend or slicing, `left = A[ : len(A)/2]` – Uri Goren Aug 06 '17 at 17:56
  • Although you are probably doing this as a learning exercise, there is always `sort(A)`. Also, you should probably read this: https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating – Alexander Aug 06 '17 at 18:09

1 Answers1

3

The problem is that you are appending list inside list.

Try this: A=[17,15,5,20,99,100]

left=[];right=[]
left = A[ : len(A)/2   ]           # Here I made change
#right.append(A[ len(A)/2  : ])

print "Left Before Sort : ",left

for j in range(len(left)):
        key=left[j]
        i=j-1
        while (i>=0 and left[i]>key):
            left[i+1]=left[i]
            i -=1
        left[i+1]=key




print "Left After Sort ",left

Output

Left Before Sort :  [17, 15, 5]
Left After Sort  [5, 15, 17]

And if you really want to append then try appending each element one by one:

for i in A[:len(A)/2]:
    left.append(i)
Shashank
  • 1,105
  • 1
  • 22
  • 35