Linear Search In Kotlin

Linear search, also known as sequential search, is a simple search algorithm that searches an array or list of elements sequentially from the beginning to the end. It compares each element of the array or list with the target element until a match is found or until all the elements have been searched.

In linear search, the array or list does not need to be sorted. The algorithm simply checks each element one by one until it finds the target element, or until it reaches the end of the array or list.

Linear search has a time complexity of O(n), where n is the number of elements in the array or list. This means that the time it takes to search for an element in an array or list using linear search increases linearly with the size of the array or list.

Although linear search is a simple and easy-to-implement algorithm, it is not efficient for large datasets as the search time can be quite slow. However, it is still useful for small datasets or when the data is unsorted.

Kotlin
fun linearSearch(arr: IntArray, target: Int): Int {
    for (i in arr.indices) {
        if (arr[i] == target) {
            return i
        }
    }
    return -1 // target not found in the array
}

The linearSearch function takes an array of integers arr and a target integer target, and returns the index of the target element in the array if it exists. If the target element is not found, the function returns -1.

The function iterates through the array using a for loop and checks each element against the target value. If it finds a match, it returns the index of that element. If it reaches the end of the loop without finding a match, it returns -1 to indicate that the target value is not in the array.

You can call this function like this:

Kotlin
fun main() {
    val arr = intArrayOf(2, 5, 8, 12, 16)
	val target = 8
	val index = linearSearch(arr, target)
	if (index != -1) {
    		println("Target found at index $index")
		} 
    else {
    		println("Target not found in the array")
		}
}

In this example, the linearSearch function is used to search for the integer value 8 in an array of integers. The function returns the index of the element containing the target value, which is 2. The output of the code is “Target found at index 2”.

Complete Code :

Kotlin
fun main() {
    val arr = intArrayOf(2, 5, 8, 12, 16)
	val target = 8
	val index = linearSearch(arr, target)
	if (index != -1) {
    		println("Target found at index $index")
		} 
    else {
    		println("Target not found in the array")
		}
}
fun linearSearch(arr: IntArray, target: Int): Int {
    for (i in arr.indices) {
        if (arr[i] == target) {
            return i
        }
    }
    return -1 // target not found in the array
}

Leave a Comment