Insertion Sort

In this sorting algorithm, we check every element with it's previous element. If it is lesser than the previous element than we swap. We keeping swapping until the element achieves it's proper place.
It's time complexity is O(n^2).
In case the given list is already sorted, this algorithm works very fast.
A simple code implementation is:-
def insertionSort(l):
  for i in range(len(l)):
    pos=i
    while(l[pos]>l[pos-1] and pos>0):
      (l[pos],l[pos-1])=(l[pos-1],l[pos])
      pos-=1
  return l

Comments

Popular posts from this blog

Rotating a list

Prime partitioning a number

Sum of prime numbers in list