In this piece of code, we will be learning to quote our logic to implement the insertion sort using python.

It is less efficient on large lists than advanced algorithms such as quicksort, heapsort, or merge sort.  

    Algorithm:

  1. Define a function named insort(a).
  2. Use for loop, with range(1, len(a)).
  3. Use while loop and check a[j],a[j+1]=a[j+1],a[j] then j is decremented.
  4. Use the function to sort the array.
  5. Using for loop, print the array.
  6. Exit 

Code:

def insort(a):

    for i in range(1, len(a)):

        b=a[i]

        j=i-1

        while j>=0 and b<a[j]:

            a[j],a[j+1]=a[j+1],a[j]

            j -= 1

        

a = [ 5, 6, 4, 1,3,2] 

insort(a) 

for i in a:

    print (i)

Output:

1

2

3

4

5

6

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019