File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 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)
You can’t perform that action at this time.
0 commit comments