bauer2010
bauer2010

Reputation: 73

Python Insertion Sort Confusion

I have this code:

Array = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

for c in range(1, len(Array)):
     if(Array[c]==-1):
         continue
     temp = Array[c]
     i = c
     d = c-1
     while(d>=0):
        if(Array[d]==-1):
            d-=1
            continue
        if(temp>=Array[d]):
            break
        Array[i] = Array[d]
        i = d
        d-=1
     Array[i] = temp

When I run the code as written, the final Array is:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

However, when I change the last line to "Array[i] = Array[c]" instead of "Array[i] = temp", the final Array is:

[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

This doesn't make sense to me. If "temp" IS Array[c], why does changing that line make this difference?

Upvotes: 0

Views: 60

Answers (1)

Fred Foo
Fred Foo

Reputation: 363817

temp gets the value of Array[c], but then the storage location Array[c] is overwritten with another value by the first execution of Array[i] = Array[d] (since i==c initially). temp is there to preserve the initial value so you can use it later on, even though Array[c] itself has been reset.

Upvotes: 4

Related Questions