Python: Performance comparison of Bubble , Insertion, and Selection sort

Result:

CompareSortingAlgos(5000)
starting bubble sort
7.0024003982543945
starting insertion sort
0.0020003318786621094
starting selection sort
1.8681068420410156

Code

def SelectionSort(alist):

    for i in range(0, len(alist) - 1):

        min = i

        for j in range(i+1, len(alist)):

            if( alist[j] < alist[min]):

                min = j

        if min != i:

            temp = alist[i]

            alist[i] = alist[min]

            alist[min] = temp

    return alist

def insertionSort(alist):

    for i in range(0,len(alist)):

        key = alist[i]

        j = i - 1

        while j>=0 and alist[j]>key:

            alist[j+1] = alist[j]

            j = j - 1

        alist[j+1] = key

    return alist

def BubbleSort(alist):

    for i in range(0,len(alist)):

        swap = 0

        for j in range(0,len(alist)-1-i):

            if(alist[j]>alist[j+1]):

                temp = alist[j]

                alist[j] = alist[j+1]

                alist[j+1] = temp

                swap = swap + 1

        if(swap == 0):

            break
       
    return alist



def CompareSortingAlgos(limit):

    import random

    import time

    l = []

    for i in range (0, limit):

        n = int((random.gauss(4,2) * 10000) % 999)

        l = l + [n]

    print("starting bubble sort")

    start = time.time()

    j = BubbleSort(l)

    print(time.time() - start)

    print("starting insertion sort")

    start = time.time()

    k = insertionSort(l)

    print(time.time() - start)

    print("starting selection sort")

    start = time.time()

    l = SelectionSort(l)

    print(time.time() - start)

Comments

Popular posts from this blog

Khuda Karay K Meri Arz -e- Pak Par Utray

میرے بعد بہت سناٹا ہوگا

Yaar Ko Hamne Ja Baja Dekha (+ lyrics)