-
Notifications
You must be signed in to change notification settings - Fork 108
/
MaxAlgorithm.kt
44 lines (36 loc) · 1008 Bytes
/
MaxAlgorithm.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
package other
import java.lang.IllegalArgumentException
/**
*
* Algorithm for finding the maximum value from a list
*
*/
class MaxAlgorithm {
fun <T : Comparable<T>> compute(items: List<T>) : T {
if (items.isEmpty()) {
throw IllegalArgumentException("items list is empty!")
}
var max = items[0]
for (i in 1 until items.size) {
if (max < items[i]) {
max = items[i]
}
}
return max
}
/**
* returns the maximum element from the list recursively
*/
fun <T : Comparable<T>> computeRecursive(items: List<T>) : T {
if (items.isEmpty()) {
throw IllegalArgumentException("items list is empty!")
}
if (items.size == 1) {
return items.first()
}
val first = items.first()
val others = items.subList(1, items.size)
val max = computeRecursive(others)
return if (first > max) first else max
}
}