Linear Search Algorithm + Code | DSA

Search in Numbers:

public class Main {
    public static void main(String[] args) {
        int[] arr = {2, 93, 52, 11, 19, 3, 41, 5, 17};
        int target = 3;
        int ans = linearSearch(arr, target);
        System.out.println(ans);
        System.out.println(linearSearch2(arr, target));
        System.out.println(linearSearch3(arr, target));
    }

    // Search in the array and return the item's index, otherwise return -1
    static int linearSearch(int[] arr, int target) {
        if(arr.length == 0) {
            return -1;
        }

        // Run a for loop
        for (int index = 0; index < arr.length; index++) {
            // Check for element at every index if it is = target
            int element = arr[index];
            if(element == target) {
                return index;
            }

        }
        //This line will execute if none of the return statements above have executed
        // hance the target not found
        return -1;
    }

    // Search in the array and return the elememt, otherwise return -1
    static int linearSearch2(int[] arr, int target) {
        if(arr.length == 0) {
            return -1;
        }

        // Run a for loop
        for (int index = 0; index < arr.length; index++) {
            // Check for element at every index if it is = target
            int element = arr[index];
            if(element == target) {
                return element;
            }

        }
        //This line will execute if none of the return statements above have executed
        // hance the target not found
        return -1;
    }

    // Search the target and return true or false
    static boolean linearSearch3(int[] arr, int target) {
        if(arr.length == 0) {
            return false;
        }

        // Run a for loop
        for (int element : arr) {
            if(element == target) {
                return true;
            }

        }
        //This line will execute if none of the return statements above have executed
        // hance the target not found
        return false;
    }
}

Search in String:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String str = "Hello World";
        char target = 'H';
        boolean ans = linearSearch(str, target);
        System.out.println(ans);
        System.out.println(linearSearch2(str, target));
        // Print str in form of character array
        System.out.println(Arrays.toString(str.toCharArray()));
    }

    // Search in String and return true or false
    static boolean linearSearch(String str, char target) {
        if (str.length() == 0) {
            return false;
        }

        for (int index = 0; index < str.length(); index++) {
            char lowerCase = Character.toLowerCase(target); // Convert user input to lower case
            if(lowerCase == str.toLowerCase().charAt(index)) {
                return true;
            }
        }
        return false;
    }

    // Search in String and return true or false
    static boolean linearSearch2(String str, char target) {
        if (str.length() == 0) {
            return false;
        }

        for (int ch : str.toCharArray()) { // For each loop
            if(ch == target) {
                return true;
            }
        }
        return false;    
    }
}

Search in Range:

public class Main {
    public static void main(String[] args) {
        // Search for 7 in the range of index [1,4]
        int[] arr = {45, 34, 97, 7, 2, 21, 78};
        int target = 7;
        int start = 1;
        int end = 4;
        int ans = linearSearch(arr, target, start, end);
        System.out.println(ans);
    }

    // Check if a value exists within a specified range in an array and return true or false
    static int linearSearch(int[] arr, int target, int start, int end) {
        if (arr.length == 0) {
            return -1;
        }

        for (int index = start; index <= end; index++) {
            int element = arr[index];
            if(target == element) {
                return index;
            }
        }
        return -1;
    }
}

Q: Find minimum value.

public class Main {
    public static void main(String[] args) {
        int[] arr = {45, 34, 97, 7, 2, 21, 78};
        System.out.println(searchMin(arr));
    }

    // Assuming array is not empty
    static int searchMin (int[] arr) { // Return the minimum value in the array
        int min = arr[0]; // Assuming the first element of an array holds the minimum value
        for (int i=1; i<arr.length; i++) {
            if (arr[i] < min) {
                min = arr[i];
            }
        }
        return min;
    }
}

Q: Search in 2D Array.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] arr = {
            {34, 56, 78},
            {1, 54, 6, 45},
            {8, 4, 2, 3, 65}
        };
        int target = 2;
        int[] ans = search(arr, target);
        System.out.println(Arrays.toString(ans));
    }

    static int[] search(int[][] arr, int target) {
        for (int row = 0; row < arr.length; row++) {
            for (int col = 0; col < arr[row].length; col++) {
                if (arr[row][col] == target) {
                    return new int[]{row, col};
                }
            }
        }
        return new int[]{-1, -1};
    }
}

Q: Find maximum number in 2D array.

public class FindMaxIn2DArray {
public static void main(String[] args) { int[][] arr = { {34, 56, 78}, {1, 54, 6, 45}, {8, 4, 2, 3, 65} }; System.out.println(searchMax(arr)); } static int searchMax(int[][] arr) { // int max = arr[0][0]; // Assuming the first element of an array holds the maximum value. // OR int max = Integer.MIN_VALUE; // output: -2147483648 // for (int row = 0; row < arr.length; row++) { // for (int col = 0; col < arr[row].length; col++) { // if (arr[row][col] > max) { // max = arr[row][col]; // } // } // } // OR Enhanced for loop for (int[] row : arr) { for (int col : row) { if (col > max) { max = col; } } } return max; } }

Q: Given an array nums of integers, return how many of them contain an even number of digits  (LeetCode Question).

public class EvenDigits {
public static void main(String[] args) { // LeetCode Question // Q: Given an array nums of integers, return how many of them contain an even number of digits. int[] nums = {12, 345, 2, 6, 7896}; System.out.println(findNumbers(nums)); } static int findNumbers (int[] nums) { int count = 0; for (int num : nums) { if (evenDigit(num)) { count++; } } return count; } //Function to check whether a number containes even digits or not static boolean evenDigit (int num) { int noOfDigits = digits2(num); // if (noOfDigits % 2 == 0) { // return true; // } // return false; // OR direct return return noOfDigits % 2 == 0; } static int digits (int num) { if (num < 0) { num *= -1; } if (num == 0) { return 1; } int count = 0; while(num > 0) { num /= 10; count++; } return count; } // Optimize the code, use digits2 insteads of digits function static int digits2(int num) { if (num < 0) { num *= -1; } return (int)(Math.log10(num)) + 1; } }

Q: Find maximum wealth (LeetCode Question).

public class MaxWealth {
public static void main(String[] args) { // LeetCode Question int[][] accounts = { {1,2,3}, {3,2,1} }; System.out.println(maximumWealth(accounts)); } static int maximumWealth(int[][] accounts) { int max = Integer.MIN_VALUE; for (int person = 0; person < accounts.length; person++) { int sum = 0; for (int account = 0; account < accounts[person].length; account++) { sum += accounts[person][account]; } // Now we have sum of accounts of person // Check with overall ans if (sum > max) { max = sum; } } return max; } }


Post a Comment

0 Comments