Question

Basically i'm trying to write an insertion sort algorithm in python and I have no idea where i'm going wrong

#!/usr/bin/env python
# coding: utf-8
import random
Array = random.sample(range(30), 5)
First = 1
Last = len(Array)
PositionOfNext = Last – 1
while PositionOfNext >= First:
    Next = Array(PositionOfNext)
    Current = PositionOfNext
    while (Current < Last) and (Next > Array[Current] + 1):
        Current = Current + 1
        (Array[Current] - 1) = Array[Current]
    Array[Current] = Next
    PositionOfNext = PositionOfNext - 1
print Array
Was it helpful?

Solution

Fixing some syntax issues and some of the indices.

Also replacing:

(Array[Current] - 1) = Array[Current]

by:

Array[Current - 1], Array[Current] = Array[Current], Array[Current - 1]

The code completed

#!/usr/bin/env python
# coding: utf-8
import random
Array = random.sample(range(30), 5)
print Array
First = 0
Last = len(Array) - 1
PositionOfNext = Last - 1
while PositionOfNext >= First:
    Next = Array[PositionOfNext]
    Current = PositionOfNext
    while  (Current < Last) and (Array[Current] > Array[Current + 1]):
        Current = Current + 1
        Array[Current - 1], Array[Current] = Array[Current], Array[Current - 1]
    Array[Current] = Next
    PositionOfNext = PositionOfNext - 1
print Array

OTHER TIPS

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)

The Insertion Sort

How about:

def insertion_sort(x):
    # insertion sort
    # we can optimize for desc, asc if we want to
    # advantages: online, O(nk) for nearly sorted
    x_sorted = [x[0]]
    x_unsorted = x[1::]
    for xx in x_unsorted:
        x_sorted.append(xx) # make room, and/or assume a sorted input list
        for i in range(len(x_sorted)-1):
            if xx < x_sorted[i]: # asc?
                x_sorted[i+1::] = x_sorted[i:-1] # shift old values
                x_sorted[i] = xx # insert new
                break # nothing to do in the inner loop form here on out
            i += 1
    return x_sorted
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top