Linear search is one of the simplest search algorithms. It sequentially checks each element in a list until the desired element (the target) is found or the list ends. This approach works on both sorted and unsorted lists, making it versatile for small datasets.
-1
).Scenario | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | The target is the first element in the list. |
Average Case | O(n) | The target is somewhere in the middle of the list. |
Worst Case | O(n) | The target is the last element or is not present at all. |
https://drawtocode.vercel.app/problems/linear-search
Loading component...
Loading component...
INPUT: [8, 3, 5, 4, 2, 7, 6, 1] ,3
OUTPUT: 1
public static void main(String args[]){
int arr[] = { 12, 11, 13, 5, 6, 7 };
int ans = linearSearch( arr,5);
if (ans == -1) {
System.out.print("Element is not present in array");
}//If End
else {
System.out.print("Element is present at index " + ans );
}//Else End
}//function end
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}//If End
}//Loop End
return -1;
}//function end
Utility Function is not required.