top of page
Subham Das

Insertion Sort


Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.

Sorting is typically done in-place, by iterating up the array, growing the sorted list behind it. At each array-position, it checks the value there against the largest value in the sorted list (which happens to be next to it, in the previous array-position checked). If larger, it leaves the element in place and moves to the next. If smaller, it finds the correct position within the sorted list, shifts all the larger values up to make a space, and inserts into that correct position.



# Program for Insertion Sort

a=[16,78,42,3,90,56,34]

for i in a :

j = a.index(i)

for j in range(j,0,-1) :

if a[j-1] > a[j] :

a[j-1],a[j] = a[j],a[j-1]

else :

break

j = j-1

print(a)






8 views0 comments

Recent Posts

See All

Comments


logo12.PNG
bottom of page