linearsearchjava.md
· 1.4 KiB · Markdown
Raw
```java
public class LinearSearch {
// Method that performs linear search
public static int linearSearch(int[] array, int target) {
// Iterate through each element in the array
for (int i = 0; i < array.length; i++) {
// If current element matches target, return its index
if (array[i] == target) {
return i;
}
}
// If target is not found, return -1
return -1;
}
// Main method to test the linear search
public static void main(String[] args) {
// Test array
int[] numbers = {4, 2, 7, 1, 9, 5, 3, 8, 6};
// Test cases
int target1 = 7; // exists in array
int target2 = 10; // doesn't exist in array
// Search for target1
int result1 = linearSearch(numbers, target1);
if (result1 != -1) {
System.out.println("Element " + target1 + " found at index " + result1);
} else {
System.out.println("Element " + target1 + " not found in array");
}
// Search for target2
int result2 = linearSearch(numbers, target2);
if (result2 != -1) {
System.out.println("Element " + target2 + " found at index " + result2);
} else {
System.out.println("Element " + target2 + " not found in array");
}
}
}
```
public class LinearSearch {
// Method that performs linear search
public static int linearSearch(int[] array, int target) {
// Iterate through each element in the array
for (int i = 0; i < array.length; i++) {
// If current element matches target, return its index
if (array[i] == target) {
return i;
}
}
// If target is not found, return -1
return -1;
}
// Main method to test the linear search
public static void main(String[] args) {
// Test array
int[] numbers = {4, 2, 7, 1, 9, 5, 3, 8, 6};
// Test cases
int target1 = 7; // exists in array
int target2 = 10; // doesn't exist in array
// Search for target1
int result1 = linearSearch(numbers, target1);
if (result1 != -1) {
System.out.println("Element " + target1 + " found at index " + result1);
} else {
System.out.println("Element " + target1 + " not found in array");
}
// Search for target2
int result2 = linearSearch(numbers, target2);
if (result2 != -1) {
System.out.println("Element " + target2 + " found at index " + result2);
} else {
System.out.println("Element " + target2 + " not found in array");
}
}
}