Given an Array, [2, 3, 4, 10, 40] and a number: 4
Write a Program to search the number in an Array.
The Program should return the index of the number, if the number is found
The program should return -1, if the number is not found.
Solution in Scala:
package in.olc.searching
object _1_1LinearSearch {
def search(arr: Array[Int], num: Int): Int = {
for (i <- 0 until arr.length) {
if (arr(i) == num) {
return i
}
}
-1
}
def main(args: Array[String]): Unit = {
val arr = Array(2, 3, 4, 10, 40)
val num = 5
val pos = search(arr, num)
pos match {
case -1 => println(s"$num not found in the array")
case index => println(s"$num found at index $index")
}
}
}
Time Complexity: O(n)
Space Complexity: O(1)
Please feel free to share your solution in the comment section.
Published By : Suraj Ghimire