-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSearch.kt
More file actions
37 lines (32 loc) · 771 Bytes
/
Copy pathLinearSearch.kt
File metadata and controls
37 lines (32 loc) · 771 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
package search
/**
* name: linear search algorithm
*
* worst time: n
* amount of memory: 1
*/
class LinearSearch<T : Comparable<T>> : Search<T> {
/**
* returns true if the element was found in the array
*
* @array - sorted array
* @element - search element
*/
override fun exists(array: Array<T>, element: T) : Boolean {
return search(array, element) != -1
}
/**
* returns the index of the searched element, otherwise -1
*
* @array - sorted array
* @element - search element
*/
override fun search(array: Array<T>, element: T) : Int {
for (i in array.indices) {
if (element == array[i]) {
return i
}
}
return -1
}
}