Skip to content

Commit a351eab

Browse files
Аdd bogo sort (#655)
1 parent dc7ff42 commit a351eab

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -954,6 +954,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute.
954954
##### Functions:
955955

956956
1. [`Bubble`](./sort/bubblesort.go#L9): Bubble is a simple generic definition of Bubble sort algorithm.
957+
1. [`Bogo`](./sort/bogosort.go#L32): Bogo generates random permutations until it guesses the correct one.
957958
2. [`Bucket`](./sort/bucketsort.go#L7): Bucket sorts a slice. It is mainly useful when input is uniformly distributed over a range.
958959
3. [`Comb`](./sort/combSort.go#L17): Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm.
959960
4. [`Count`](./sort/countingsort.go#L11): No description provided.

sort/bogosort.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// This is a pure Go implementation of the bogosort algorithm,
2+
// also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort.
3+
// Bogosort generates random permutations until it guesses the correct one.
4+
5+
// More info on: https://en.wikipedia.org/wiki/Bogosort
6+
7+
package sort
8+
9+
import (
10+
"math/rand"
11+
12+
"github.com/TheAlgorithms/Go/constraints"
13+
)
14+
15+
func isSorted[T constraints.Number](arr []T) bool {
16+
for i := 0; i < len(arr)-1; i++ {
17+
if arr[i] > arr[i+1] {
18+
return false
19+
}
20+
}
21+
22+
return true
23+
}
24+
25+
func shuffle[T constraints.Number](arr []T) {
26+
for i := range arr {
27+
j := rand.Intn(i + 1)
28+
arr[i], arr[j] = arr[j], arr[i]
29+
}
30+
}
31+
32+
func Bogo[T constraints.Number](arr []T) []T {
33+
for !isSorted(arr) {
34+
shuffle(arr)
35+
}
36+
37+
return arr
38+
}

sort/sorts_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,11 @@ func TestBubble(t *testing.T) {
8585
testFramework(t, sort.Bubble[int])
8686
}
8787

88+
func TestBogo(t *testing.T) {
89+
t.Skip("Skipping test for Bogo Sort, as it uses a lot of resource.")
90+
testFramework(t, sort.Bogo[int])
91+
}
92+
8893
func TestBucketSort(t *testing.T) {
8994
testFramework(t, sort.Bucket[int])
9095
}
@@ -230,6 +235,11 @@ func BenchmarkBubble(b *testing.B) {
230235
benchmarkFramework(b, sort.Bubble[int])
231236
}
232237

238+
func BenchmarkBogo(b *testing.B) {
239+
b.Skip("Skipping benchmark for Bogo Sort, as it uses a lot of resource.")
240+
benchmarkFramework(b, sort.Bogo[int])
241+
}
242+
233243
func BenchmarkBucketSort(b *testing.B) {
234244
benchmarkFramework(b, sort.Bucket[int])
235245
}

0 commit comments

Comments
 (0)