3.2 KiB
3.2 KiB
Review 1
- Hajin Ju, 2024062806
Problem 1
1 Fill in the blank entries when the numbers are sorted by insertion sort in non-decreasing order.
from bs4 import BeautifulSoup as bs
data = [
[(7, False), (4, False), (3, False), (6, False), (8, False), (1, False), (2, False)],
[(7, True), (4, False), (3, False), (6, False), (8, False), (1, False), (2, False)],
[(4, True), (7, True), None, None, None, None, None],
]
soup = bs("<div></div>", 'lxml')
td_style = "border: 1px solid black; padding: 10px; text-align: center; font-size: 1.2rem; min-width: 3rem;"
td_style_high = "border: 1px solid black; padding: 10px; text-align: center; font-size: 1.2rem; min-width: 3rem; background-color: lightgray;"
for i in range(3):
table = soup.new_tag("table")
table["style"] = "display: flex; justify-content: center;"
tr = soup.new_tag("tr")
for d in data[i]:
td = soup.new_tag("td")
if d:
td['style'] = td_style_high if d[1] else td_style
td.string = str(d[0]) if d else " "
else:
td["style"] = td_style
td.string = " "
tr.append(td)
table.append(tr)
soup.div.append(table)
print(soup.prettify())
Solution 1
from bs4 import BeautifulSoup as bs
data = [
[(7, False), (4, False), (3, False), (6, False), (8, False), (1, False), (2, False)],
]
# insertion sorting process
for i in range(len(data[0])):
cur = data[-1].copy()
cur[i] = (cur[i][0], True)
key = cur[i][0]
while i > 0:
i -= 1
if key >= cur[i][0]:
break
else:
temp = cur[i + 1]
cur[i + 1] = cur[i]
cur[i] = temp
data.append(cur)
soup = bs("<div></div>", 'lxml')
td_style = "border: 1px solid black; padding: 10px; text-align: center; font-size: 1.2rem; min-width: 3rem;"
td_style_high = "border: 1px solid black; padding: 10px; text-align: center; font-size: 1.2rem; min-width: 3rem; background-color: lightgray;"
for i in range(len(data)):
table = soup.new_tag("table")
table["style"] = "display: flex; justify-content: center;"
tr = soup.new_tag("tr")
for d in data[i]:
td = soup.new_tag("td")
if d:
td['style'] = td_style_high if d[1] else td_style
td.string = str(d[0]) if d else " "
else:
td["style"] = td_style
td.string = " "
tr.append(td)
table.append(tr)
soup.div.append(table)
print(soup.prettify())
Problem 2
Fill in the blanks with proper number of iterations.
Solution 2
// INSERTION-SORT(A) // cost // number of iterations
for j = 2 to n // c1 // n - 1
key = A[j] // c2 // n - 1
i = j - 1 // c3 // n - 1
while i > 0 and A[i] > key // c4 // tj
A[i + 1] = A[i] // c5 // tj - 1
i = i - 1 // c6 // tj - 1
A[i + 1] = key // c7 // n - 1
Problem 3
What is the running time of insertion sort when the input size is n?
Solution 3
-
best case:
\theta(n)t_j = 1 -
worst case:
\theta(n^2)t_j = j