-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsorting_algorithms.py
81 lines (56 loc) · 1.78 KB
/
sorting_algorithms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# -*- coding: utf-8 -*-
"""
@author: jalbert
Implementation of three sorting algorithms with complexity 0(n^2) and the comparasion of time execution between them.
"""
import random
from time import time
lst = [random.randint(0, 200) for x in range(50)]
def bubble_sort(array):
for i in range(len(array)):
for j in range(len(array)-1-i):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array
def insertion_sort(array):
for i in range(len(array)):
j = i
while j > 0 and array[j] < array[j-1]:
array[j], array[j-1] = array[j-1], array[j]
j -= 1
return array
def selection_sort(array):
for slot in range(len(array)-1,0,-1):
maxpos = 0
for index in range(slot+1):
if array[index] > array[maxpos]:
maxpos = index
temp = array[slot]
array[slot] = array[maxpos]
array[maxpos] = temp
return array
t0 = time()
bubble_sort(lst)
ft0 = time()
elapsed0 = ft0 - t0
print "Bubble sort algorithm"
print "Execution time: %.10f sec" % (elapsed0)
print "==================================="
t1 = time()
insertion_sort(lst)
ft1 = time()
elapsed1 = ft1 - t1
print "Insertion sort algorithm"
print "Execution time: %.10f sec" % (elapsed1)
print "==================================="
t2 = time()
selection_sort(lst)
ft2 = time()
elapsed2 = ft2 - t2
print "Selection sort algorithm"
print "Execution time: %.10f sec" % (elapsed2)
print "===================================\n"
algorithms = {'Bubble': elapsed0, 'Insertion': elapsed1, 'Selection': elapsed2}
print "From best algorithm to worst:\n"
for key, value in sorted(algorithms.iteritems(), key=lambda (k,v): (v,k)):
print "%s: %s" % (key, value)