public class LinearSearchExample
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40, 50};
int key = 30;
boolean found = false;
// Linear search
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == key)
{
System.out.println("Element found at index: " + i);
found = true;
break;
}
}
if (!found)
{
System.out.println("Element not found");
}
}
}
Element found at index: 2
Case | Description | No. of Comparisons | Time Complexity |
---|---|---|---|
Worst Case | The element is either at the last position or not present in the array. | n |
O(n) |
Average Case | The element is found somewhere in the middle of the array. | n/2 |
ฮ(n) |
Best Case | The element is found at the first position. | 1 |
ฮฉ(1) |
O(1)
โ only a few variables are used; no extra memory is needed.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.