Skip to content

Commit 9083bb9

Browse files
Feat: add Bogo Sort (#79)
* add nim bogo sort * style: apply nimpretty to bogo_sort.nim * style: add newline at end of bogo_sort.nim
1 parent af31828 commit 9083bb9

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

sorts/bogo_sort.nim

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
## Bogo Sort
2+
## =============
3+
## wiki: https://en.wikipedia.org/wiki/Bogosort
4+
##
5+
{.push raises: [].}
6+
7+
runnableExamples:
8+
9+
var arr = @[3, 1, 2]
10+
bogoSort(arr)
11+
doAssert isSorted(arr)
12+
13+
var arr2 = @["c", "a", "b"]
14+
bogoSort(arr2)
15+
doAssert isSorted(arr2)
16+
17+
18+
import random
19+
20+
func isSorted[T](arr: openArray[T]): bool =
21+
for i in 0..<arr.len - 1:
22+
if arr[i] > arr[i + 1]:
23+
return false
24+
return true
25+
26+
proc bogoSort*[T](arr: var openArray[T]) =
27+
while not isSorted(arr):
28+
shuffle(arr)
29+
30+
when isMainModule:
31+
import std/unittest
32+
suite "BogoSortTests":
33+
test "sort an array of integers":
34+
var arr = @[3, 1, 2]
35+
bogoSort(arr)
36+
check isSorted(arr)
37+
38+
test "sort an array of strings":
39+
var arr = @["c", "a", "b"]
40+
bogoSort(arr)
41+
check isSorted(arr)

0 commit comments

Comments
 (0)