Here\'s a Python implementation of insertion sort, I tried to follow the values on paper but once the counting variable i gets bigger than len(s) I don\'t know what to do, h
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]
print(alist)
position -= 1
alist[position] = currentvalue
alist = [int(i) for i in input().split()]
insertionSort(alist)
Insertion Sort via Recursion:
k=1# def insertionsort(a): # should be written before k=1
c=a[:]
def swap(k,c,a):
if c[k-1] > c[k]:
c[k-1] = a[k]
c[k] = a[k-1]
a = c[:]
if max(c[:k])!= c[k-1]:
swap(k-1,c,a)
if k < len(a)-1:
return swap(k + 1, c,a)
return c
return swap(k,c,a)
print(insertionsort(b))
Try this one, works for both increasing and decreasing order:
import operator
def insertion_sort(arr, reverse=False):
# check if array is empty or not
if arr is None:
raise TypeError("Data cannot be none")
n = len(arr)
# if length of array is less than two it is already sorted
if n < 2:
return arr
lgt = operator.gt if reverse else operator.lt
# Traverse through 1 to len(arr)
for i in range(1, n):
key = arr[i]
j = i-1
while j >= 0 and lgt(key, arr[j]):
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
li = [1, 4, 8, 9, 42, 0, 36]
print(insertion_sort(li))
If we consider an array from left to right [LeftMost, ..., RightMost], an insertion sort performs the following procedure for each item:
This is the key of the sort algorithm. Once you are done processing at item i, you have a sorted array from where it originally was all the way to the beggining (left most).
Sidenote (not important to understand the algorithm, but could be useful): With that in mind, you can deduce that this algorithm's complexity (measured in worst case comparisons) is O(N^2) where N = len(s). It is similar to having two nested for statements.
This video does a great job explaining the above, and you know what they say, an image is worth 1000 words.
def insertionsort(list):
for i in range(1,len(list)):
temp=list[i]
j=i-1
while temp<+list[j] and j>=0:
list[j+1]=list[j]
j=j-1
list[j+1]=temp
return list
list=eval(raw_input('Enter a list:'))
print insertionsort(list)
This will help you.
def insertion(x):
for i in range(1, len(x)):
while x[i - 1] > x[i] and i >= 0:
x[i - 1], x[i] = x[i], x[i - 1]
i -= 1
return x
Something like that