Reputation: 6071
I wrote this insertion sort, but for some reason it doesn't return anything, and I can't figure out why. Could someone take a look at this?
def insertionSort(lis):
for i in range (1, len(lis)):
j = i - 1
value = lis[i]
while j >= 0:
if value < lis[j]: #have to be value because the number has to remain the same
lis[j+1] = lis[j]
j-= 1
else:
lis[j+1] = value
return lis
Upvotes: 0
Views: 106
Reputation: 59232
You have an infinite loop. In this code:
while j >= 0:
if value < lis[j]: #have to be value because the number has to remain the same
lis[j+1] = lis[j]
j-= 1
else:
lis[j+1] = value
as soon as you reach a point where value < lis[j]
is false, j
is not decremented and your while
loop will never exit.
I can write a correct insertion sort for you if you want, but I think that would defeat the point of you trying to do it yourself.
Upvotes: 3
Reputation: 906
Please take a look at this sample code ,It maybe helpful for you
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
Upvotes: -1