Skip to content

Commit 258b108

Browse files
c252jiegillet
authored andcommitted
implemented bogo sort in nim (#355)
* implemented bogo sort in nim and fixed a formatting problem in book.json
1 parent a1a078d commit 258b108

File tree

3 files changed

+33
-3
lines changed

3 files changed

+33
-3
lines changed

book.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,10 +132,10 @@
132132
"lang": "lisp",
133133
"name": "Lisp"
134134
},
135-
{
136-
"lang": "nim",
135+
{
136+
"lang": "nim",
137137
"name": "Nim"
138-
}
138+
}
139139
]
140140
}
141141
}

contents/bogo_sort/bogo_sort.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ In code, it looks something like this:
3939
[import:25-31, lang:"swift"](code/swift/bogosort.swift)
4040
{% sample lang="php" %}
4141
[import:11-16, lang:"php"](code/php/bogo_sort.php)
42+
{% sample lang="nim" %}
43+
[import:16-18, lang:"nim"](code/nim/bogo_sort.nim)
4244
{% endmethod %}
4345

4446
That's it.
@@ -77,6 +79,8 @@ We are done here!
7779
[import, lang:"swift"](code/swift/bogosort.swift)
7880
{% sample lang="php" %}
7981
[import, lang:"php"](code/php/bogo_sort.php)
82+
{% sample lang="nim" %}
83+
[import, lang:"nim"](code/nim/bogo_sort.nim)
8084
{% endmethod %}
8185

8286

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import random
2+
3+
randomize()
4+
5+
proc print_array(a: openArray[int]) =
6+
for n in 0 .. len(a)-1:
7+
echo a[n]
8+
9+
proc is_sorted(a: openArray[int]): bool =
10+
for n in 1 .. len(a)-1:
11+
if a[n] > a[n-1]:
12+
return false
13+
14+
return true
15+
16+
proc bogo_sort(a: var openArray[int]) =
17+
while not is_sorted(a):
18+
shuffle(a)
19+
20+
21+
var x: array[10,int] = [32,32,64,16,128,8,256,4,512,2]
22+
23+
print_array(x)
24+
bogo_sort(x)
25+
echo "\n"
26+
print_array(x)

0 commit comments

Comments
 (0)