When we try to find an element in a collection by checking each element of the collection one by one, we refer to this way of searching as a linear search. We can perform a linear search for both unordered and ordered collections.
Linear search
Linear search in an unordered collection
As the elements in an unordered collection are not in a clear and logical order, we've to check each element until we find the required one. The code for such a linear search will look like the following:
fun <E> Collection<E>.linearSearch(element: E): Int {
for ((index, value) in this.withIndex()) {
if (value == element) return index
}
return -1
}
One thing to note here is that the function is defined as an extension...