Advertisement
ralphdc09

its101.md.wk.08.09.LinearSearch

Nov 15th, 2021
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.69 KB | None | 0 0
  1. package its101.mdwk08_09;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class LinearSearch {
  6.  
  7.     //    Create function linearSearch()
  8.     public static int linearSearch(int[] arr, int key) {
  9.         for (int i = 0; i < arr.length; i++) {
  10.             //  If key is found, return its index position
  11.             if (arr[i] == key) {
  12.                 return i;
  13.             }
  14.         }
  15.         //  If key is not found then return -1
  16.         return -1;
  17.     } //    End of function linearSearch()
  18.  
  19.     public static void main(String[] args) {
  20.         //  Create new array
  21.         int[] myArray = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170};
  22.  
  23.         //  Print array
  24.         System.out.println(Arrays.toString(myArray));
  25.  
  26.         //  Initiate key to be search for in the array
  27.         int key1 = 110;
  28.         //  Call function linearSearch() to perform linear search in the array
  29.         int result = linearSearch(myArray, key1);
  30.  
  31.         //  If-else statement for printing the result
  32.         if (result != -1) {
  33.             System.out.println("Element " + key1 + " is present at index " + result);
  34.         } else {
  35.             System.out.println("Element " + key1 + "is not present in the array");
  36.         }
  37.  
  38.         //  Initiate new key to be search for in the array
  39.         int key2 = 175;
  40.         //  Call function linearSearch() to perform linear search again
  41.         int result2 = linearSearch(myArray, key2);
  42.  
  43.         //  If-else statement for printing the result
  44.         if (result2 != -1) {
  45.             System.out.println("Element " + key2 + " is present at index " + result2);
  46.         } else {
  47.             System.out.println("Element " + key2 + " is not present in the array");
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement