Implement Insertion Sort using Python

If you’re in a computer science background, widening your technical horizons is the best thing you should do. However, your programming skills matter the most and one must continuously keep sharpening these skills. And to become a better programmer in the future. Though there are multiple things to focus on, one specific area you must focus on is the world of data structures. Data structures in general are specific approaches to solve problems in such a way that computer resources get used minimum. In general, there are multiple data structures you can learn and implement as well. However, to keep things simple were going to start with some basic programs you must learn before moving on to complex algorithms. Therefore today we’re going to learn how to Implement Insertion Sort using Python.

 

What is Insertion Sort?

 

  • Comes in the list of simplest data structure, Insertion Sort is the way of arranging elements in ascending order. The array is either sorted or is unsorted.

 

  • When the array is sorted this data structure works quickest. However, when elements aren’t sorted it works the slowest.

 

What’s The Approach?

 

  • Consider arr[n] of size n we want to implement Insertion Sort on. So firstly we’ll iterate a loop from 1 to n.

 

  • Next, we’ll compare the element at iterating index with its preceding element from the array. If the comparing element is smaller, we’ll again compare it with the before elements.

 

  • Lastly, Move the greater elements one position up to make space for the swapped element.

 

Also Read: Implement Linked List using Java

 

Python Program To Implement Insertion Sort

 

Input:

 

12, 11, 13, 5, 6

 

Output:

 

5 6 11 12 13

 

# Python program for implementation of Insertion Sort

# Function to do insertion sort
def insertionSort(arr):

    # Traverse through 1 to len(arr)
    for i in range(1, len(arr)):

        key = arr[i]

        # Move elements of arr[0..i-1], that are
        # greater than key, to one position ahead
        # of their current position
        j = i-1
        while j >= 0 and key < arr[j] :
                arr[j + 1] = arr[j]
                j -= 1
        arr[j + 1] = key


# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
    print ("% d" % arr[i])

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

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