fork download
  1. public class Main {
  2. public static int linearSearch(int[] array, int target) {
  3. for (int i = 0; i < array.length; i++) {
  4. if (array[i] == target) {
  5. return i; // Element found, return its index
  6. }
  7. }
  8. return -1; // Element not found in the array
  9. }
  10.  
  11. public static void main(String[] args) {
  12. int[] array = {10, 5, 7, 2, 8, 4, 1};
  13. int targetElement = 8;
  14.  
  15. int result = linearSearch(array, targetElement);
  16.  
  17. if (result != -1) {
  18. System.out.println("Element " + targetElement + " found at index " + result);
  19. } else {
  20. System.out.println("Element " + targetElement + " not found in the array");
  21. }
  22. }
  23. }
Success #stdin #stdout 0.16s 55432KB
stdin
Standard input is empty
stdout
Element 8 found at index 4