Hello Buddies
Let's implement a simple linear search.
As the name suggests, it will traverse in 1D and it keeps on iterating until the element is found.
public
class
LinearSearch {
public
static
void
main(String[] args)
{
int[]
sortedArray
= { 1, 2, 3, 4, 9, 99, 100 };
int
element
= 999;
int
idx
= findIndex(sortedArray,
element);
System.out.println("Index
: "
+ idx);
}
private
static
int
findIndex(int[]
sortedArray,
int
element)
{
for
(int
i
= 0; i
< sortedArray.length;
i++)
{
if
(sortedArray[i]
== element)
{
return
i;
}
}
return
-1;
}
}
Some details to keep in mind -
Worst-case performance O(n)
Best-case performance O(1)
Average performance O(n)
Worst-case space complexity O(1) iterative
Source : Wiki
Happy Coding!
No comments:
Post a Comment