Skip to content
Snippets Groups Projects
Commit ccbb83fa authored by Dominik Zobel's avatar Dominik Zobel Committed by Tobias Koelling
Browse files

Possible code examples for bubble and merge sort

parent f61ef24e
No related branches found
No related tags found
1 merge request!24complexity lecture
...@@ -57,6 +57,71 @@ Tree[^1] $\mathcal{O}(\log{n})$ $\mathcal{O}(\log{n})$ ...@@ -57,6 +57,71 @@ Tree[^1] $\mathcal{O}(\log{n})$ $\mathcal{O}(\log{n})$
* bisect (?) (ref to `git bisect`) * bisect (?) (ref to `git bisect`)
## Bubble Sort
```{python}
#| echo: true
def Bubble_Sort(values):
num_elements = len(values)
for idx_cur_elem in range(num_elements):
for i in range(num_elements-idx_cur_elem-1):
if (values[i] > values[i+1]):
values[i], values[i+1] = values[i+1], values[i]
print(values)
testvec = [6, 0, 3, 1, 5, 7, 4, 2]
Bubble_Sort(testvec)
```
## Merge Sort (1/2)
:::{.smaller}
```{python}
#| echo: true
def Merge_Join(values, idx_left, idx_split, idx_right):
left_temp = values[idx_left:idx_split+1]
right_temp = values[idx_split+1:idx_right+1]
idx_temp_left = 0
idx_temp_right = 0
idx_overall = idx_left
while (idx_temp_left < idx_split-idx_left+1) and (idx_temp_right < idx_right-idx_split):
value_left = left_temp[idx_temp_left]
value_right = right_temp[idx_temp_right]
if (value_left <= value_right):
values[idx_overall] = value_left
idx_temp_left += 1
else:
values[idx_overall] = value_right
idx_temp_right += 1
idx_overall += 1
if (idx_temp_left < idx_split-idx_left+1):
values[idx_overall:idx_right+1] = left_temp[idx_temp_left:]
elif (idx_temp_right < idx_right-idx_split):
values[idx_overall:idx_right+1] = right_temp[idx_temp_right:]
print(values)
```
:::
## Merge Sort (2/2)
```{python}
#| echo: true
def Merge_Sort(values, idx_left, idx_right):
if (idx_left < idx_right):
idx_split = (idx_left+idx_right) // 2
Merge_Sort(values, idx_left, idx_split)
Merge_Sort(values, idx_split+1, idx_right)
Merge_Join(values, idx_left, idx_split, idx_right)
testvec = [6, 0, 3, 1, 5, 7, 4, 2]
Merge_Sort(testvec, 0, len(testvec)-1)
```
# models of computation # models of computation
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment