Kotlin program for linear search: Linear search is very simple, to check if an element is present in the given list we compare it with every element in the list.
If it is found then we print the location at which it occurs, otherwise, the list doesn't contain the element we are searching for.
Linear search is the simplest search algorithm; it is a special case of brute-force search. Its worst-case cost is proportional to the number of elements in the list.
For Example, When we are looking for a specific element from the list/collection, we have to go each index and check whether given value is equal or not.
If the required element is present at the end of the list then we have to go each and every address till the end, so we have to compare the values till the end. If list/collection has 100 elements then we have to compare elements 100 times.
Its expected cost is also proportional to the number of elements if all elements are searched equally.
If the list has more than a few elements and is searched often, then more complicated search methods such as binary search or hashing may be appropriate. Those methods have faster search times but require additional resources to attain that speed.
Below example showcases the Linear search in Kotlin.
for ((index, value) in list.withIndex()) {
if (value == key){
return index
}
fun linearSearch(list:List<Any>, key:Any):Int?{
for ((index, value) in list.withIndex()) {
if (value == key){
return index
}
}
return null
}
fun main(args: Array<String>) {
println("\nOrdered list:")
val someList = listOf(9, 7, "Adam", "Clark", "John", "Tim", "Zack", 6)
println(someList)
val name = 7
val position = linearSearch(someList, name)
println("${name} is in the position ${position} in the ordered List.\n")
val name2 = "Tim"
val position2 = linearSearch(someList, name2)
println("${name2} is in the position ${position2} in the ordered List.\n")
}