Python Program for Insertion Sort


Insertion sort is not the best sorting algorithm in terms of performance. But this is slightly more efficient than selection sort and bubble sort.


Python Program to Implement Insertion Sort

# Python program to implement  Insertion Sort 
  
# Function for insertion sort 
def insertion_Sort(num_arr): 
  
    # Traversing elements from 1 to len(arr) 
    for j in range(1, len(num_arr)): 
  
        temp = num_arr[j] 

        k = j-1
        while k >=0 and temp < num_arr[k] : 
                num_arr[k+1] = num_arr[k] 
                k -= 1
        num_arr[k+1] = temp 
  
  
alist = [42, 10, 9, 15, 26,11,13,5] 
insertion_Sort(alist) 
print ("Sorted array Elements are:") 
for i in range(len(alist)): 
    print ("%d" %alist[i])

Output:-

Sorted array Elements are:
5
9
10
11
13
15
26
42

 


 

Leave a Reply

Your email address will not be published. Required fields are marked *