Monday, 21 November 2016

Sequential search or linear search and its performance

Linear search is the simplest approach. Given a array or collection you try every element in the collection until you have found the input or until you reach the end of the collection.

Linear search is very easy to implement.


Example:

public class LinearSearch {

public static boolean search(int[] input, int element) {
for (int i : input) {
if (i == element) {
return true;
}
}
return false;
}

public static void main(String[] args) {
int input[] = {67,67,89,12,34,56};
System.out.println(search(input, 89));
System.out.println(search(input, 34));
System.out.println(search(input, 100));
}


}


Performance:

Best Case :- O(1) (if the element found in the first element of the array or collection).
Average Case and Worst case : O(n) (where n is the number of elements in array or collection).


Click to view more:-  Algorithms and its performance

No comments:

Post a Comment

s