I wrote a little program that inserts an element in a list. The program uses a binary search algorithm to find the spot where the new element should be allocated. I’m having trouble to change the original list content. What’s wrong in my code?
JavaScript
x
10
10
1
def Insert(TAB,V):
2
3
for i in range(0, len(TAB)):
4
5
j, count = binarySearch(TAB,V)
6
7
TAB = TAB[:j] + [V] + TAB[j:]
8
9
return "index =",j,"comparisons =", count
10
Advertisement
Answer
JavaScript
1
2
1
TAB = TAB[:j] + [V] + TAB[j:]
2
This builds a new list and assigns it to the local variable TAB
. IF you expect to change the list in the calling program, then you have to operate directly on that list, not assign to its local avatar.
JavaScript
1
2
1
TAB.insert(j, V)
2
should do the job.