Linear Search Algorithm

The Linear Search Algorithm, also known as the Sequential Search Algorithm, is a fundamental searching technique used for finding a specific element within a list or an array of elements. The algorithm works by iterating through each element in the list or array, comparing it with the target value. If the element being examined matches the target value, the algorithm stops and returns the index of the matching element. If the algorithm reaches the end of the list or array without finding the target element, it returns an indication that the value was not found, such as -1 or null. The primary advantage of the Linear Search Algorithm is its simplicity, as it requires no prior knowledge of the data structure or any specific ordering of the elements within the list or array. This makes it particularly useful for small datasets, unsorted lists, or when searching for multiple occurrences of a target value. However, the algorithm's performance can be quite slow for large datasets, as it has a worst-case time complexity of O(n), where n is the number of elements in the list or array. In such cases, more efficient search algorithms like Binary Search or Hash-based searching techniques can be employed for better performance.
/*
 * Copyright (c) 2017 Kotlin Algorithm Club
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.algorithmexamples.search

class LinearSearch<T>: AbstractSearchStrategy<T>() {
    override fun perform(arr: Array<T>, element: T): Int {
        for ((i, a) in arr.withIndex()) {
            if (a == element) {
                return i
            }
        }
        return -1
    }
}

LANGUAGE:

DARK MODE: