-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem3.py
More file actions
90 lines (74 loc) · 2.18 KB
/
Copy pathproblem3.py
File metadata and controls
90 lines (74 loc) · 2.18 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
problem = "problem3"
student_name = "Abudi Alshamam"
student_numer = "N1212353"
"""
source of bubble sort, selection sort and mrge sort code:
@author: ericgrimson
"""
import random
num_comparisson = 0
def bubble_sort(L):
global num_comparisson
num_comparisson = 0
swap = False
while not swap:
swap = True
for j in range(1, len(L)):
if L[j-1] > L[j]:
num_comparisson += 1
swap = False
temp = L[j]
L[j] = L[j-1]
L[j-1] = temp
def selection_sort(L):
global num_comparisson
num_comparisson = 0
suffixSt = 0
while suffixSt != len(L):
for i in range(suffixSt, len(L)):
if L[i] < L[suffixSt]:
num_comparisson += 1
L[suffixSt], L[i] = L[i], L[suffixSt]
suffixSt += 1
def merge(left, right):
global num_comparisson
result = []
i,j = 0,0
while i < len(left) and j < len(right):
num_comparisson += 1
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while (i < len(left)):
num_comparisson += 1
result.append(left[i])
i += 1
while (j < len(right)):
num_comparisson += 1
result.append(right[j])
j += 1
return result
def merge_sort(L):
global num_comparisson
num_comparisson = 0
if len(L) < 2:
return L[:]
else:
middle = len(L)//2
left = merge_sort(L[:middle])
right = merge_sort(L[middle:])
return merge(left, right)
def sort_comparison(list_size, sorted=False):
global num_comparisson
sort_list = [random.randint(0, 100) for i in range(list_size)]
print('List of size ' + str(list_size) + ' to sort is: ' + str(sort_list))
bubble_sort(sort_list[:])
print(f'Number of comparisons for bubble sort: {num_comparisson}')
selection_sort(sort_list[:])
print(f'Number of comparisons for selection sort: {num_comparisson}')
merge_sort(sort_list[:])
print(f'Number of comparisons for merge sort: {num_comparisson}')
sort_comparison(20)