Bubble/Insert/Selection sort by Python

import time


# -----------Bubble sort--------------------
s = time.clock()
a = [4, 2, 5, 6, 1, 3, 7, 12, 34, 2, 234,5, 13, 2]
n = len(a)

for i in range(n-1, 0 , -1):
    for j in range(i):
        if a[j] > a[j+1]:
            temp = a[j]
            a[j] = a[j+1]
            a[j+1] = temp

print a
e = time.clock()

print 'Time used: ', e-s


# ----------Insert sort-----------------------
s = time.clock()
a = [4, 2, 5, 6, 1, 3, 7, 12, 34, 2, 234,5, 13, 2]
n = len(a)
for i in range(n):
    current = a[i]
    while i>0 and a[i]<a[i-1]:
        a[i] = a[i-1]
        a[i-1] = current
        i = i-1

print a
e = time.clock()

print 'Time used: ', e-s


# -----------Selection sort---------------------
s = time.clock()
a = [4, 2, 5, 6, 1, 3, 7, 12, 34, 2, 234,5, 13, 2]
n = len(a)
for i in range(n-1):
    minValue = a[i]
    for j in range(i+1,n):
        if a[j]<minValue:
            a[i] = a[j]
            a[j] = minValue
            minValue = a[i]

print a
e = time.clock()

print 'Time used: ', e-s

 

posted @ 2017-12-08 07:41  YWU  阅读(156)  评论(0)    收藏  举报