Code

Linear Search Algorithm
1
public class LinearSearch {
2
int linearSearch(int list[], int targetElement) {
3
for (int i = 0; i < list.length; i++) {
4
if (list[i] == targetElement) {
5
return i; // Element found, return its index
6
}
7
}
8
return -1; // Element not found
9
}
10
11
public static void main(String args[]) {
12
LinearSearch ls = new LinearSearch();
13
int list[] = {2, 3, 4, 10, 40};
14
int targetElement = 10;
15
int result = ls.linearSearch(list, targetElement);
16
if (result != -1) {
17
System.out.println('Element found at index ' + result);
18
}
19
else {
20
System.out.println('Element not found');
21
}
22
}
23
}

Canvas

Code visualizations will appear here.

Algorithm Description

This program demonstrates the Linear Search algorithm, a simple technique to search for an element in a list. It sequentially checks each element of the list until the target is found or the end of the list is reached. If the target element is found, its index is returned; otherwise, -1 indicates it was not found. This approach is commonly used for small or unsorted data.
Time Complxity:  O(n)

Real-Life Use Cases

  • Finding a Contact in a Phonebook: When searching for a contact in a small, unsorted list, a linear search can quickly locate the contact by checking each entry one by one.
  • Checking Attendance: In schools or events, a linear search can be used to verify if a specific individual's name appears on a manually sorted or unsorted attendance list.
  • Inventory Lookup: In a small retail shop, linear search can be used to find a specific item in an unsorted inventory list. For instance, checking if a product with a specific ID or name is available.