-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPreclasswork1.2
68 lines (59 loc) · 2.04 KB
/
Preclasswork1.2
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
import random
import sys
import time
integer = 7
def random_list(integer):
lst = []
for x in range (integer):
lst.append(random.randint(0, 100))
return lst
def insertion_sort(lst):
count_insertion_sort = 0
for index in range(1, len(lst)):
key = lst[index]
pos = index-1
while pos >=0 and key < lst[pos]:
lst[pos+1] = lst[pos]
pos += -1
count_insertion_sort += 1
lst[pos+1] = key
print "sorted array:", lst
print "Number of steps to sort this list using insertion sort:", count_insertion_sort
def selection_sort(lst):
count_selection_sort = 0
for i in range(len(lst)):
min_index = i
for j in range(i+1, len(lst)):
if lst[j] < lst[min_index]:
min_index = j
count_selection_sort += 1
lst[i], lst[min_index] = lst[min_index], lst[i]
print "sorted array:", lst
print "Number of steps to sort this list using selection sort:", count_selection_sort
def bubble_sort(lst):
count_bubble_sort = 0
for i in range(len(lst)):
for j in range(0, len(lst)-i-1):
count_bubble_sort += 1
if lst[j] > lst[j+1]:
lst[j],lst[j+1] = lst[j+1],lst[j]
print "sorted array:", lst
print "Number of steps to sort this list using bubble sort:", count_bubble_sort
start_insertion_sort = time.time()
lst = random_list(integer)
print "random array:", lst
insertion_sort(lst)
end_insertion_sort = time.time()
print "Time insertion sort takes:", (end_insertion_sort-start_insertion_sort), "seconds"
start_selection_sort = time.time()
lst = random_list(integer)
print "random array:", lst
selection_sort(lst)
end_selection_sort = time.time()
print "Time selection sort takes:", (end_selection_sort-start_selection_sort), "seconds"
start_bubble_sort = time.time()
lst = random_list(integer)
print "random array:", lst
bubble_sort(lst)
end_bubble_sort = time.time()
print "Time bubble sort takes:", (end_bubble_sort-start_bubble_sort), "seconds"