⬅ Previous Topic
Selection SortNext Topic ⮕
Merge Sort⬅ Previous Topic
Selection SortNext Topic ⮕
Merge SortTopic Contents
Given an array of integers, your task is to sort the array in non-decreasing order using the Insertion Sort algorithm.
Insertion Sort builds the final sorted array one element at a time. It is much like sorting playing cards in your hands — you take one card at a time and insert it into its correct position relative to the cards already sorted.
Your goal is to understand how Insertion Sort compares elements, shifts them, and places each item into its correct location during the sorting process.
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
if __name__ == '__main__':
arr = [6, 3, 8, 2, 7, 4]
insertion_sort(arr)
print("Sorted array is:", arr)
⬅ Previous Topic
Selection SortNext Topic ⮕
Merge SortYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.