Wednesday, 22 March 2017

Linear Search Implementation in Java


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

Featured post

JAVA based project, that can be used to hit DB using JDBC, from WSO2 ESB

Hi Buddies, Here is a small project that will enable you to hit MySQL DB using WSO2 ESB - https://github.com/namitsharma99/customM...