Linear search is a straightforward searching algorithm. In this we
iterate through all the elements of array sequentially to find the matching element.
The elements of array can be in any order. Its time complexity is O(n)
read as Order of n.
Average case time complexity of Linear search is O(n/2)
Worst case time complexity of Linear search is O(n)
/**
* Returns a positive index if the search element is
* available in the given array otherwise returns -1.
*
* @param list
* @param searchEle
* @return
*/ public static int linearSearch(int[] list, int searchEle) {
int index = -1; for (int i = 0 ; i < list.length ; i ++) { if (list[i] == searchEle) {
index = i; break;
}
}
System.out.println(searchEle + " found in array at index : " + index); return index;
}
}
It gives the following output,
Array : [6, 5, 1, 8, 3, 9, 4, 0, 2, 7]
2 found in array at index : 8
8 found in array at index : 3
12 found in array at index : -1