Linear Search in Kotlin | Data Structures

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.

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 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 in end of the list then we have to go each and every address till the end, so the we have to compare the values till 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.

linear-search in kotlin Below example showcases the Linear search in Kotlin.

  • Get the list to a function or we can do it in a main function itself
  • Once we have the array/list, we have to iterate through the elements of the array/list, in this example we are using the for loop with index
  • 
    								for ((index, value) in list.withIndex()) {
    								
  • While iterating we have to compare the target element with the current element in the iteration
  • 
    								if (value == key){
    									return index
    								}
    								
  • If current element and target element matches then we got our index of the target element
  • If there is no match then we will return null as result

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")
}			

About Author

This article is written by Pavan, who is serving notice period in an MNC, Bangalore. He thought, let the articles speak rather than his image. He is also the same person who created the reporter for Protractor Jasmine

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions