xxxxxxxxxx
# Python program for implementation of Insertion Sort
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >= 0 and key < arr[j] :
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
print ("% d" % arr[i])
# This code is contributed by Mohit Kumra
xxxxxxxxxx
#Insertion sort
ar = [34, 42, 22, 54, 19, 5]
for i in range(1, len(ar)):
while ar[i-1] > ar[i] and i > 0:
ar[i-1], ar[i] = ar[i], ar[i-1]
i -= 1
print(ar)
xxxxxxxxxx
def insertion_sort(array):
for i in range(1, len(array)):
x = array[i]
while x < array[i - 1] and i > 0:
array[i] = array[i - 1]
i -= 1
array[i] = x
xxxxxxxxxx
# Insertion sort
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
lst = []
print("Sorted array is : ")
for i in range(len(arr)):
lst.append(arr[i]) #appending the elements in sorted order
print(lst)
j = i-1
print(range(len(arr)))
print(i)
print(arr[j])
xxxxxxxxxx
# Python program for implementation of Insertion Sort
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >= 0 and key < arr[j] :
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
print ("% d" % arr[i])
# This code is contributed by Mohit Kumra