Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package its101.mdwk08_09;
- import java.util.Arrays;
- public class LinearSearch {
- // Create function linearSearch()
- public static int linearSearch(int[] arr, int key) {
- for (int i = 0; i < arr.length; i++) {
- // If key is found, return its index position
- if (arr[i] == key) {
- return i;
- }
- }
- // If key is not found then return -1
- return -1;
- } // End of function linearSearch()
- public static void main(String[] args) {
- // Create new array
- int[] myArray = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170};
- // Print array
- System.out.println(Arrays.toString(myArray));
- // Initiate key to be search for in the array
- int key1 = 110;
- // Call function linearSearch() to perform linear search in the array
- int result = linearSearch(myArray, key1);
- // If-else statement for printing the result
- if (result != -1) {
- System.out.println("Element " + key1 + " is present at index " + result);
- } else {
- System.out.println("Element " + key1 + "is not present in the array");
- }
- // Initiate new key to be search for in the array
- int key2 = 175;
- // Call function linearSearch() to perform linear search again
- int result2 = linearSearch(myArray, key2);
- // If-else statement for printing the result
- if (result2 != -1) {
- System.out.println("Element " + key2 + " is present at index " + result2);
- } else {
- System.out.println("Element " + key2 + " is not present in the array");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement