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
#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
"""
This is an implementation of the insertion sort
algorithm.
Idea is to grow a sorted subset from one element
and then pull all elements of array into that
sorted subset while keeping that subset sorted.
Let n be the size of the list to sort
Time complexity: O(n^2),
Space complexity: O(1)
"""
def insertion_sort(arr):
for idx in range(1, len(arr)):
scan = idx
while scan > 0 and arr[scan] < arr[scan-1]:
swap(arr, scan, scan-1)
scan -= 1
return arr
def swap(arr, idx1, idx2):
arr[idx1], arr[idx2] = arr[idx2], arr[idx1]
arr_to_sort = [1, 10, 3, 2]
print(insertion_sort(arr_to_sort)) # [1, 2, 3, 10]
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
# 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