Skip to content
Snippets Groups Projects
Commit 195c3461 authored by nilsl99's avatar nilsl99
Browse files

Added exercise08_2

parent 914abcb6
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## OOP Homework 08
### Exercise 2
Dilay Hamaykaya, Nils Liebreich, Aleksandr Reznik
%% Cell type:code id: tags:
``` python
import random
import matplotlib.pyplot as plt
```
%% Cell type:markdown id: tags:
#### (b)
%% Cell type:code id: tags:
``` python
def isort(a):
for i in range(len(a)):
# füge a[i] an der richtigen Stelle in a[0], ..., a[i] ein
left = 0
right = i
if a[i] >= a[0]:
while right - left > 1:
middle = (left+right) // 2
if a[middle] > a[i]:
right = middle
else:
left = middle
a.insert(right, a.pop(i))
else:
a.insert(0, a.pop(i))
```
%% Cell type:code id: tags:
``` python
nums = list(range(100))
a = random.choices(nums, k=10)
print(a)
isort(a)
print(a)
```
%% Output
[80, 41, 90, 56, 15, 35, 97, 4, 2, 50]
[2, 4, 15, 35, 41, 50, 56, 80, 90, 97]
%% Cell type:markdown id: tags:
#### (c) and (d)
%% Cell type:code id: tags:
``` python
def isort(a):
comparisons = 0
swaps_assum1 = 0
swaps_assum2 = 0
for i in range(len(a)):
# füge a[i] an der richtigen Stelle in a[0], ..., a[i] ein
left = 0
right = i
comparisons += 1
if a[i] >= a[0]:
while right - left > 1:
middle = (left+right) // 2
comparisons += 1
if a[middle] > a[i]:
right = middle
else:
left = middle
swaps_assum1 += 2
swaps_assum2 += i - right
a.insert(right, a.pop(i))
else:
swaps_assum1 += 2
swaps_assum2 += i - right
a.insert(0, a.pop(i))
return comparisons, swaps_assum1, swaps_assum2
```
%% Cell type:code id: tags:
``` python
nums = list(range(100))
comparisons = []
swaps_assum1 = []
swaps_assum2 = []
n_list = list(range(1, 30))
for n in n_list:
split = [isort(a) for a in (random.choices(nums, k=n) for _ in range(1000))]
comp, swap1, swap2 = zip(*split)
comparisons.append(sum(comp)/len(comp))
swaps_assum1.append(sum(swap1)/len(swap1))
swaps_assum2.append(sum(swap2)/len(swap2))
```
%% Cell type:code id: tags:
``` python
fig, ax = plt.subplots()
fig.suptitle("Complexity of Binary Insertion Sort")
ax.grid(axis="y")
ax.set_xlabel("length of the list")
ax.set_ylabel("average costs in the respected machine model")
ax.plot(n_list, comparisons, "o", fillstyle="none", label="Comparisons")
ax.plot(n_list, swaps_assum2, "x", label="Swaps (Assumption 1)")
ax.plot(n_list, swaps_assum1, "+", label="Swaps (Assumption 2)")
ax.legend()
fig.tight_layout()
plt.savefig("exercise08_2c.png", dpi=200)
plt.show()
```
%% Output
exercise08_2c.png

103 KiB

0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment