Skip to content

Commit 9133a55

Browse files
Ariana1729berquist
authored andcommitted
Added bubblesort in bash (#509)
1 parent 6e9e386 commit 9133a55

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

contents/bubble_sort/bubble_sort.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ This means that we need to go through the vector $$\mathcal{O}(n^2)$$ times with
6464
[import:3-14, lang:"scala"](code/scala/bubble_sort.scala)
6565
{% sample lang="emojic" %}
6666
[import:2-14, lang:"emojicode"](code/emojicode/bubble_sort.emojic)
67+
{% sample lang="bash" %}
68+
[import:2-21, lang:"bash"](code/bash/bubble_sort.bash)
6769
{% endmethod %}
6870

6971
... And that's it for the simplest bubble sort method.
@@ -133,6 +135,8 @@ Trust me, there are plenty of more complicated algorithms that do precisely the
133135
[import, lang:"scala"](code/scala/bubble_sort.scala)
134136
{% sample lang="emojic" %}
135137
[import, lang:"emojicode"](code/emojicode/bubble_sort.emojic)
138+
{% sample lang="bash" %}
139+
[import, lang:"bash"](code/bash/bubble_sort.bash)
136140
{% endmethod %}
137141

138142
<script>
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env bash
2+
bubble_sort() {
3+
local i
4+
local j
5+
local tmp
6+
local len
7+
local arr
8+
arr=("$@")
9+
(( len = ${#arr[@]} ))
10+
11+
for ((i = 0; i <= len - 1; i++)); do
12+
for ((j = 0; j <= len - 2; j++)); do
13+
if (( arr[j] > arr[(( j + 1 ))] )); then
14+
(( tmp = arr[(( j + 1 ))] ))
15+
(( arr[(( j + 1 ))] = arr[j] ))
16+
(( arr[j] = tmp ))
17+
fi
18+
done
19+
done
20+
echo ${arr[*]}
21+
}
22+
23+
arr=(1 45 756 4569 56 3 8 5 -10 -4)
24+
echo "Unsorted array: ${arr[*]}"
25+
tmp=$(bubble_sort "${arr[@]}")
26+
echo "Sorted array: ${tmp[*]}"

0 commit comments

Comments
 (0)