Skip to content
Advertisement

Implementing Insertion sort in Python

I am trying to write the insertion sort algorithm ( without the help of the solution in the book) and so far came up with this algorithm, when I matched it with the solution, it looks different. This is the code I wrote:

def insertSor(n):
    key = 0
    while key < len(n):
        for j in range(len(n)-1):
            if n[j] > n[j+1]:
                n[j], n[j+1] = n[j+1], n[j]
        key = key+1
    return n


print(insertSor([2, 1, 0, 8, 9, 5]))

Is this code still valid as an insertion sort?

Algo in the book:

for j = 2 to A.length
    key = A[j]
    i=j-1

    while i > 0 and A[i]>key
       A[i+1]=A[i]
       i = i - 1
    A[i+1]=key

Advertisement

Answer

Looks like a bubble sort to me

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement