insertion sort with python code example
Example 1: insertion sort in python
def insertion(s):
for i in range(0,len(s)-1):
if s[i]>s[i+1]:
s[i],s[i+1]=s[i+1],s[i]
for j in range(i,0,-1):
if s[j]<s[j-1]:
s[j],s[j-1]=s[j-1],s[j]
print(s)
insertion([5,2,1,9,0,4,6])
Example 2: insertion sort python
def insertionSort(alist):
for i in range(1,len(alist)):
current = alist[i]
while i>0 and alist[i-1]>current:
alist[i] = alist[i-1]
i = i-1
alist[i] = current
return alist
print(insertionSort([5,2,1,9,0,4,6]))
Example 3: insertion sort in python
def tri_insert(tab):
for i in range(1, len(tab)):
k = tab[i]
j = i-1
while j >= 0 and k < tab[j] :
tab[j + 1] = tab[j]
j -= 1
tab[j + 1] = k
return tab