Skip to content

Added Bubblesort in Coconut #736

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions contents/bubble_sort/bubble_sort.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ This means that we need to go through the vector $$\mathcal{O}(n^2)$$ times with
[import:1-6, lang:"coffeescript"](code/coffeescript/bubblesort.coffee)
{% sample lang="r" %}
[import:1-12, lang:"r"](code/r/bubble_sort.R)
{% sample lang="coco" %}
[import:3-10, lang:"coconut"](code/coconut/bubblesort.coco)
{% endmethod %}

... And that's it for the simplest bubble sort method.
Expand Down Expand Up @@ -159,6 +161,8 @@ The code snippet was taken from this [Scratch project](https://scratch.mit.edu/p
[import, lang:"coffeescript"](code/coffeescript/bubblesort.coffee)
{% sample lang="r" %}
[import, lang:"r"](code/r/bubble_sort.R)
{% sample lang="coco" %}
[import, lang:"coconut"](code/coconut/bubblesort.coco)
{% endmethod %}

<script>
Expand Down
16 changes: 16 additions & 0 deletions contents/bubble_sort/code/coconut/bubblesort.coco
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import random

def swap_till(x, []) = [x]

addpattern def swap_till(x, y is int) = [min(x, y), max(x, y)]

addpattern def swap_till(x, [y] + rest) =
[min(x, y)] + swap_till(max(x, y), rest)

bubble_sort = reduce$((x, y) -> swap_till(y, x))

if __name__ == '__main__':
array = range(10) |> map$(-> random.randint(0, 1000)) |> list
print('Before sorting:', array)
array = bubble_sort(array) |> list
print('After sorting:', array)