Insertion Sort

Insertion sort is based on the idea that one element from the input elements is consumed in each iteration to find its correct position i.e, the position to which it belongs in a sorted array.

The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.

This is done by shifting all the elements, which are larger than the current element, in the sorted array to one position ahead

Algorithm:

To sort an array of size n in ascending order:


1: Iterate from arr[1] to arr[n] over the array.

2: Compare the current element (key) to its predecessor.

3: If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.


Example:



Time Complexities:

  • Worst Case Complexity: O(n2)
    If we want to sort in ascending order and the array is in descending order then, the worst case occurs.

  • Best Case Complexity: O(n)
    It occurs when the array is already sorted

  • Average Case Complexity: O(n2)
    It occurs when the elements of the array are in jumbled order (neither ascending nor descending)


Program:

L=[]

def get():
n=int(input("Enter no of Elements"))

for i in range(n):
no = int(input("Enter no"))
L.append(no)


def dis():
for i in L:
print(i,end=" ")


def insertion():
for i in range(1, len(L)):
k=L[i]
j=i-1
while j>=0 and k< L[j]:
L[j+1]=L[j]
j-=1
L[j+1]=k
print("\n Iteration= ",i)
print(L)



get()
dis()

insertion()

/// Output///
Enter no of ELements5
Enter no5
Enter no4
Enter no3
Enter no2
Enter no1
5 4 3 2 1 
 Iteration=  1
[4, 5, 3, 2, 1]

 Iteration=  2
[3, 4, 5, 2, 1]

 Iteration=  3
[2, 3, 4, 5, 1]

 Iteration=  4
[1, 2, 3, 4, 5]

Post a Comment

1 Comments

Yashwant said…
best teacher ever