Skip to content

Commit a33a634

Browse files
GorzoidKen Power
authored and
Ken Power
committed
Bogosort in lua (algorithm-archivists#413)
* Added Bogosort * Fixed code Wasn't running * Added tests Same as bubble sort. * Adding entry to bogo_sort.md * Addressing changes bogo_sort.md corrected, properly implemented Fisher–Yates shuffle * Remove unnecessary line specification Line numbers not needed when importing entire file
1 parent c0ed22b commit a33a634

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

contents/bogo_sort/bogo_sort.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ In code, it looks something like this:
3131
[import:17-20, lang:"haskell"](code/haskell/bogoSort.hs)
3232
{% sample lang="m" %}
3333
[import:21-28, lang:"matlab"](code/matlab/bogosort.m)
34+
{% sample lang="lua" %}
35+
[import:1-22, lang="lua"](code/lua/bogosort.lua)
3436
{% sample lang="cpp" %}
3537
[import:33-38, lang:"c_cpp"](code/c++/bogosort.cpp)
3638
{% sample lang="rs" %}
@@ -73,6 +75,8 @@ We are done here!
7375
[import, lang:"haskell"](code/haskell/bogoSort.hs)
7476
{% sample lang="m" %}
7577
[import, lang:"matlab"](code/matlab/bogosort.m)
78+
{% sample lang="lua" %}
79+
[import, lang="lua"](code/lua/bogosort.lua)
7680
{% sample lang="cpp" %}
7781
[import, lang:"c_cpp"](code/c++/bogosort.cpp)
7882
{% sample lang="rs" %}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
local function shuffle(arr)
2+
for i = 1, #arr-1 do
3+
local rand = math.random(i,#arr)
4+
arr[i], arr[rand] = arr[rand], arr[i]
5+
end
6+
end
7+
8+
local function issorted(arr)
9+
for i = 1,#arr-1 do
10+
if arr[i] > arr[i+1] then
11+
return false
12+
end
13+
end
14+
return true
15+
end
16+
17+
function bogosort(arr)
18+
while not issorted(arr) do
19+
shuffle(arr)
20+
end
21+
end
22+
23+
local arr = {1, 45, 756, 4569, 56, 3, 8, 5, -10, -4}
24+
print(("Unsorted array: {%s}"):format(table.concat(arr,", ")))
25+
26+
bogosort(arr)
27+
28+
print(("Sorted array: {%s}"):format(table.concat(arr,", ")))

0 commit comments

Comments
 (0)