-
Notifications
You must be signed in to change notification settings - Fork 108
/
BogoSort.kt
47 lines (39 loc) · 1001 Bytes
/
BogoSort.kt
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
39
40
41
42
43
44
45
46
import kotlin.random.Random
fun main(args : Array<String>) {
//Create Array
var array = intArrayOf(4,5,3,9,1)
array = sort(array)
array.forEach {
println(it)
}
}
/**
* Use Bogo sort to randomly swap two inputs and then check if the list is sorted
*/
fun sort(input:IntArray):IntArray{
//keep repeating check until sorted
while (!isSorted(input)){
//get two randomly picked array locations
val index1 = Random.nextInt(0, input.size-1)
val index2 = Random.nextInt(0, input.size-1)
//swap the values
val temp = input[index1]
input[index1] = input[index2]
input[index2] = temp
}
return input
}
/**
* Check if the array is sorted from lowest to highest
*/
fun isSorted(input:IntArray): Boolean{
var max:Int? = null
for(x in input.indices){
if(max == null || input[x] >= max){
max = input[x]
}else{
return false
}
}
return true
}