public class Main {
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i; // Element found, return its index
}
}
return -1; // Element not found in the array
}
public static void main
(String[] args
) { int[] array = {10, 5, 7, 2, 8, 4, 1};
int targetElement = 8;
int result = linearSearch(array, targetElement);
if (result != -1) {
System.
out.
println("Element " + targetElement
+ " found at index " + result
); } else {
System.
out.
println("Element " + targetElement
+ " not found in the array"); }
}
}
cHVibGljIGNsYXNzIE1haW4gewogICAgcHVibGljIHN0YXRpYyBpbnQgbGluZWFyU2VhcmNoKGludFtdIGFycmF5LCBpbnQgdGFyZ2V0KSB7CiAgICAgICAgZm9yIChpbnQgaSA9IDA7IGkgPCBhcnJheS5sZW5ndGg7IGkrKykgewogICAgICAgICAgICBpZiAoYXJyYXlbaV0gPT0gdGFyZ2V0KSB7CiAgICAgICAgICAgICAgICByZXR1cm4gaTsgLy8gRWxlbWVudCBmb3VuZCwgcmV0dXJuIGl0cyBpbmRleAogICAgICAgICAgICB9CiAgICAgICAgfQogICAgICAgIHJldHVybiAtMTsgLy8gRWxlbWVudCBub3QgZm91bmQgaW4gdGhlIGFycmF5CiAgICB9CgogICAgcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgewogICAgICAgIGludFtdIGFycmF5ID0gezEwLCA1LCA3LCAyLCA4LCA0LCAxfTsKICAgICAgICBpbnQgdGFyZ2V0RWxlbWVudCA9IDg7CgogICAgICAgIGludCByZXN1bHQgPSBsaW5lYXJTZWFyY2goYXJyYXksIHRhcmdldEVsZW1lbnQpOwoKICAgICAgICBpZiAocmVzdWx0ICE9IC0xKSB7CiAgICAgICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbigiRWxlbWVudCAiICsgdGFyZ2V0RWxlbWVudCArICIgZm91bmQgYXQgaW5kZXggIiArIHJlc3VsdCk7CiAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgU3lzdGVtLm91dC5wcmludGxuKCJFbGVtZW50ICIgKyB0YXJnZXRFbGVtZW50ICsgIiBub3QgZm91bmQgaW4gdGhlIGFycmF5Iik7CiAgICAgICAgfQogICAgfQp9