Skip to content

Commit b8c732a

Browse files
sjnestervdnhi
authored andcommitted
Update LinearSearch.scala
There are a few ways to improve this: Thanks for this resource! Just a few suggestions for readability, performance and lack of stack overflows. 1. Use a Vector - you're doing random accesses which are O(N) for Lists but O(1) for Vectors. 2. Make conditionals positive, much easier to reason about than negative conditionals 3. (2) enables the recursive call to Iter() to be last in the Iter function, which allows Iter to be tail recursive, which means no matter how long the parameter is it will never cause a stack overflow.
1 parent d4c0614 commit b8c732a

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed

src/main/scala/Search/LinearSearch.scala

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,14 @@ object LinearSearch {
1010
* @param elem - a integer to search for in the @args
1111
* @return - index of the @elem or -1 if elem is not fount in the @arr
1212
*/
13-
def linearSearch(arr: List[Int], elem: Int): Int = {
14-
def iter(index: Int): Int = {
15-
if (index != arr.length) {
16-
if (arr(index) != elem) iter(index + 1)
17-
else index
18-
} else
19-
-1
13+
def linearSearch(arr: Vector[Int], elem: Int): Int = {
14+
def iter(index: Int): Int =
15+
if (index == arr.length) -1
16+
else if (arr(index) == elem) index
17+
else iter(index + 1)
2018
}
2119

2220
iter(0)
2321
}
2422

25-
}
23+
}

0 commit comments

Comments
 (0)