1

I am working on creating a basic insertion sort algorithm using Python.

My textbook shows the psudeocode of an insertion sort algorithm here.

If I follow that convention using python 3, I produce the following code:

def insertionSort(arr):
#Traverse through 1 to len array
   for j in range(1, len(arr)):
       key = arr[j]
       i = j-1
       while i >0 and arr[i] > key:  #this line seems incorrect?
           arr[i+1] = arr[i]
           i = i-1
       arr[i+1] = key
   return arr

If I set arr = [12,11,13,5,6] The result returns as [12,5,6,11,12,13] which obviously is not a correct sort.

After tweaking with the algorithm for some time changing the line I marked as incorrect to while i>=0 and arr[i] > key: the algorithm gives the correct output. Is my book incorrect in omitting the equal sign or am I not understanding how the psuedocode operates within my textbook?

3
  • It looks like your correction is right; and if your book omitted the =, it is wrong. Commented Aug 30, 2020 at 21:08
  • @khelwood, look at the screenshot. The book is using a 1-based indexing. Both are right. Commented Aug 30, 2020 at 21:11
  • 1
    @bourbaki4481472 Yes, I saw your answer. Very perceptive. Commented Aug 30, 2020 at 21:12

2 Answers 2

2

It looks like you mostly correctly translated the book's algorithm into Python. As you see, the book's algorithm is 1-based while Python is 0-based.

The book's algorithm starts at index 2 but you have to start at index 1.

This also translates to keeping the while loop going until the first index. In the book's case, that's 1 and in your case it should be 0 in Python. So the book is correct but you are also correct (because of the differences in indexing conventions).

Sign up to request clarification or add additional context in comments.

Comments

1
def insertionSort(arr):
#Traverse through 1 to len array
   for j in range(1, len(arr)):
       key = arr[j]
       i = j-1
       # you need to change here to i>=0
       while i >= 0 and arr[i] > key:  #this line seems incorrect?
           arr[i+1] = arr[i]
           i = i-1
       arr[i+1] = key
   return arr

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.