Anonymous Anonymous - 2 months ago
159 0

Insertion Sort Algorithm implemented in python with timer function. Reads search list from file.

Python

Insertion Sort

#!/usr/bin/python
import time
from functools import wraps

def fn_timer(function):
    @wraps(function)
    def function_timer(*args, **kwargs):
        t0 = time.clock()
        result = function(*args, **kwargs)
        t1 = time.clock()
        print (t1-t0)
        return result
    return function_timer

def sortCheck(subject):
    if subject == sorted(subject):
        print "List already sorted"
    else:
        insertionSort(subject)

@fn_timer
def insertionSort(subject):
    for index in range(1,len(subject)):
        value = subject[index]
        position = index

        while position>0 and subject[position-1]>value:
            subject[position] = subject[position -1]
            position = position -1
            subject[position]=value

fileName = raw_input("Enter filename to search: ")
content = [line.rstrip('\n') for line in open(fileName)]
content = map(int, content)

sortCheck(content)
print len(content)