fork download
  1. public class Main {
  2.  
  3. private static int linearSearch(int[] list, int key) {
  4. for (int i = 0; i < list.length; i++) {
  5. if (list[i] == key) {
  6. return i;
  7. }
  8. }
  9.  
  10. return -1;
  11. }
  12.  
  13.  
  14. public static void main(String[] args) {
  15.  
  16. int[] ages = {20, 19, 18, 21, 19, 17, 16, 22};
  17. int key = 50;
  18.  
  19. int result = linearSearch(ages, key);
  20.  
  21. if (result == -1) {
  22. System.out.println("No such element");
  23. } else {
  24. System.out.println("Student with such age was found at index" + result);
  25. }
  26.  
  27. }
  28. }
Success #stdin #stdout 0.07s 54780KB
stdin
Standard input is empty
stdout
No such element