Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: Insertion Sort : Python Code & Linked List implementation

Friday, October 10, 2014

Insertion Sort : Python Code & Linked List implementation

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. Each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.
Sorting is typically done in-place, by iterating up the array, growing the sorted list behind it. At each array-position, it checks the value there against the largest value in the sorted list (which happens to be next to it, in the previous array-position checked). If larger, it leaves the element in place and moves to the next. If smaller, it finds the correct position within the sorted list, shifts all the larger values up to make a space, and inserts into that correct position.


Python Code

import random
def InsertionSort():
    N = input("Enter the number of elements in the list:")
    unsortedList = [0 for i in range(N)]
    for i in range(N):
        """ user input can be taken here"""
        unsortedList[i] = int(random.random()*N)
        i = i + 1
    print 'Unsorted list is:',unsortedList
    i = 0
    sortedList = [0 for i in range(N)]
    sortedList[0] = unsortedList[0]
    """ counter holds the number of elements inserted in the sorted list"""
    counter = 1
    for i in range (N-1):
        i = i + 1
        temp = counter
        while unsortedList[i] < sortedList[counter-1] and counter > 0:
            sortedList[counter] = sortedList[counter-1]
            counter = counter - 1
        sortedList[counter] = unsortedList[i]
        temp = temp+1
        counter = temp
    print 'Sorted list is:',sortedList           
InsertionSort()   

No comments:

Post a Comment