Categories: Algorithmpython

Implementation of Insertion Sort in Python

Insertion Sort builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.

Resources for Review

Check out the resources below for a review of Insertion sort!

def insertion_sort(arr):
    
    # For every index in array
    for i in range(1,len(arr)):
        
        # Set current values and position
        currentvalue = arr[i]
        position = i
        
        # Sorted Sublist
        while position > 0 and arr[position-1] > currentvalue:
            
            arr[position]=arr[position-1]
            position = position-1

        arr[position] = currentvalue
arr =[3,5,4,6,8,1,2,12,41,25]
insertion_sort(arr)
print(arr)

[1, 2, 3, 4, 5, 6, 8, 12, 25, 41]

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Share
Published by
Hassan Raza

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

3 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

4 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

4 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

5 months ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

5 months ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

5 months ago