Skip to content
Snippets Groups Projects
Commit 796c88f5 authored by Tobias Koelling's avatar Tobias Koelling
Browse files

refactor bubble sort

parent 04bdb09e
No related branches found
No related tags found
1 merge request!24complexity lecture
......@@ -79,13 +79,13 @@ Tree[^1] $\mathcal{O}(\log{n})$ $\mathcal{O}(\log{n})$
:::{.fragment fragment-index=1}
1. Array which has $n$ entries
1. Array with $n$ elements
:::
:::{.fragment fragment-index=2}
2. Comparing first elements. Switch elements if left element is greater than right one
2. Compare first two elements, swap them if left > right
:::
......@@ -97,7 +97,7 @@ Tree[^1] $\mathcal{O}(\log{n})$ $\mathcal{O}(\log{n})$
:::{.fragment fragment-index=4}
4. Keep repeating with $n-1$, $n-2$, ... entries until everything is sorted
4. Keep repeating until everything is sorted
:::
......@@ -106,17 +106,35 @@ Tree[^1] $\mathcal{O}(\log{n})$ $\mathcal{O}(\log{n})$
```{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)
def swap_if_larger(values):
for i in range(len(values) - 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)
:::: {.r-stack}
::: {.fragment .fade-out fragment-index=1 style="margin: 0;"}
```{python width=100%}
#| echo: true
test_values = [6, 0, 3, 5, 1]
swap_if_larger(test_values)
```
:::
::: {.fragment .fade-in fragment-index=1 style="margin: 0;"}
```{python}
#| echo: true
def bubble_sort(values):
for _ in values:
swap_if_larger(values)
test_values = [6, 0, 3, 5, 1]
bubble_sort(test_values)
```
:::
::::
## Merge Sort (1/3) {.leftalign}
......
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