0

In this picture, you can see that the code is using if A[j] > curNum: A[j+1] = A[j] , and then changing the number to 11, when in reality the code should do something different, am I crazy?

R.A.Munna
  • 1,699
  • 1
  • 15
  • 29

2 Answers2

1

In python, negative indexes in list mean that you count from the end instead of from the beginning. For example, -1 is the last item, and -2 is the second last item.

What happened there is, j is -1, so when the program executes the line,

A[j+1] = A[j]

it is doing

A[0] = A[-1]

since it wraps around when the index is negative, it grabs the last item in the list, which is 11, and hence

A[0] = 11
weichichi
  • 75
  • 8
  • Ahh ok, so this makes it inefficient correct? Is there a way i can change it to make it skip that step and go to the else statement? – GrantSweatshirt Oct 02 '17 at 21:18
  • @GrantSweatshirt The easiest way to limit it is by adding another condition ```and j >= 0``` in the if statement. However, using your example, that only saves 2 steps in total (if you also take out the ```A[j+1] = curNum``` line for reason mentioned in another answer), which might not be worth the extra evaluation. If you want to significantly improve the performance, I suggest you to take a look at [this link](https://stackoverflow.com/questions/12755568/how-does-python-insertion-sort-work). the most upvoted answer is quite elegant and efficient, with only 57 steps using the website you used. – weichichi Oct 02 '17 at 21:48
0

at line 10 after else there is no need write A[j+1] = curNum because A[k+1] = curNum line is assigning the value at desired position. And you will get a description about negative indices from here.

And Please Have a look about insertion sort algorithm from Wikipedia link. here I just copy paste the algorithm.

function insertionSortR(array A, int n)
    if n>0
        insertionSortR(A,n-1)
        x ← A[n]
        j ← n-1
        while j >= 0 and A[j] > x
            A[j+1] ← A[j]
            j ← j-1
        end while
        A[j+1] ← x
    end if
end function

And the implementation of insertion sort is like that

def insertionSortR(A):
    for i in range(1,len(A)):
        temp = A[j]
        j = i
        while j > 0 and temp < A[j-1]:
            A[j] = A[j-1]
            j=j-1
        A[j] = temp
    return A

for more implementation and discussion, take a look here

R.A.Munna
  • 1,699
  • 1
  • 15
  • 29