forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbogosort.go
More file actions
38 lines (29 loc) · 754 Bytes
/
bogosort.go
File metadata and controls
38 lines (29 loc) · 754 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// This is a pure Go implementation of the bogosort algorithm,
// also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort.
// Bogosort generates random permutations until it guesses the correct one.
// More info on: https://en.wikipedia.org/wiki/Bogosort
package sort
import (
"math/rand"
"github.com/TheAlgorithms/Go/constraints"
)
func isSorted[T constraints.Number](arr []T) bool {
for i := 0; i < len(arr)-1; i++ {
if arr[i] > arr[i+1] {
return false
}
}
return true
}
func shuffle[T constraints.Number](arr []T) {
for i := range arr {
j := rand.Intn(i + 1)
arr[i], arr[j] = arr[j], arr[i]
}
}
func Bogo[T constraints.Number](arr []T) []T {
for !isSorted(arr) {
shuffle(arr)
}
return arr
}