Linear Search In Arrays

Linear Search In Arrays

Here We Will Discuss what is Linear Search And Questions Related To It

Here In This Blog, We Will Discuss What Is Linear Search, Code Related To It And Some Questions Regarding It. These Things I Have Learnt From 13th Video Lecture of DSA Playlist By Kunal Kushwaha

Topics To Be Discussed:

Search In String

Search In Range

Search In 2d Arrays

Even Digits

Linear Search

In Linear Search Algorithm there is no prior condition that the array should be sorted, but In Sorting Algorithm such as Binary Search, there is a general assumption that Array should be sorted before.

In Linear Search Algorithm, we traverse from one end (index 0) and move toward another end (index array. length - 1), checking elements one by one and if the element is present at index I, then it returns the index i.

If the element is not present in the array, then it returns -1. This means the element is not present inside the array, also it returns -1 when the length of the array is zero.

import java.util.Scanner;

public class LinearSearch {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // Creating an integer which stores length of array
        System.out.println("Enter the number of elements in array");
        int n = input.nextInt();

        // Creating an array of size 'n'
        int[] array = new int[n];

        // Taking inputs of array
        System.out.println("Enter the elements of array");
        for (int i = 0; i < array.length; i++) {
            array[i] = input.nextInt();
        }

    // Initiating the targeting element which ig going to be found in array
        System.out.println("Enter the target element");
        int target = input.nextInt();

     // creating an integer ans which stores the index of the target element
        int ans = linearsearch(array, target);

        // Printing the output
        System.out.println("\n Target Element is present at index " + ans);

        input.close();
    }

    // Code for linear Search
    static int linearsearch(int[] arr, int element) {
        if (arr.length == 0) {
            return -1;
        }
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == element) {
                return i;
            }
        }
        return -1;
    }
}

Output:

Search In String

We can Consider String as an "array of primitive datatype", so we can search for a particular element in the string

We should remember that Strings are immutable

import java.util.*;

public class SearchInString {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter the string");
        String str = input.next();

        System.out.println("Enter the Character element ot be found in string");
        char target = input.next().charAt(0);

        // Integer which stores the position of the element
        int ans = SearchString(str, target);

        // Printing the index
     System.out.println("The Character Element is present at index: " + ans);

        input.close();
     }

    // Code for Search in Range
    static int SearchString(String str, char target) {
        if (str.length() == 0) {
            return -1;
        }
        int index;
        for (index = 0; index < str.length(); index++) {
            if (str.charAt(index) == target) {
                return index;
            }
        }
        return -1;

    }
}

Output:

Search In Range

Here we have to apply a linear search algorithm but in a specific range i.e if we have been given the first index is 2 and the last index is 6 in an array of 9 elements, then we have to search for the target element with 2 and 6, i.e for 2,3,4,5,6 index only and if the element is present then return the index of element otherwise return -1.


/*
 * Here an array is given 
 * Target is given 
 * Two indexes  one is first index and other is last index and we have to search btw those.
 */
import java.util.*;;

public class SearchInRange {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        boolean check = false;
        int first_index = 0, last_index = 0;
        int ind;

        System.out.println("Enter the string");
        String str = input.next();

        System.out.println("Enter the Target element");
        char targ = input.next().charAt(0);

        System.out.println("Enter the beginning index for search");
        first_index = input.nextInt();

        System.out.println("Enter the last index for search");
        last_index = input.nextInt();

        // Creasting an integer which stores index of the target element
        int ans = search_in_range(str, targ, first_index, last_index);

        System.out.println("\nPrinting the Index of the Target Character: " + ans);

        input.close();

    }

 static int search_in_range(String str, char target, int first_index, int last_index) {
        if (str.length() == 0) {
            return -1;
        }
        for (int i = first_index; i <= last_index; i++) {
            if (str.charAt(i) == target) {
                return i;
            }
       }
        return -1;
    }

}

Output:

Search In 2d Array

import java.util.Arrays;

public class SearchIn2DArray {
    public static void main(String[] args) {
        int[][] arr = {
                { 23, 4, 1 },
                { 18, 12, 3, 9 },
                { 78, 99, 34, 56 },
                { 18, 12 }
        };
        int target = 56;
        int[] ans = search(arr, target); // format of return value {row, col}
        System.out.println(Arrays.toString(ans));

        System.out.println(max(arr));

        System.out.println(Integer.MIN_VALUE);
    }

    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 };
    }

    static int max(int[][] arr) {
        int max = Integer.MIN_VALUE;
        for (int[] ints : arr) {
            for (int element : ints) {
                if (element > max) {
                    max = element;
                }
            }
        }
        return max;
    }
}

The Credits For Code In Search In 2d Array: Kunal Kushwaha

Output:

Even Digits

Given an array nums of integers, return how many of them contain an even number of digits.

Even is an integer initialized to zero, and increment by one when the number of digits of a element in the array is divisible by 2

Here, first of all, we will select an element of the array, then store the number of digits present in the element in the array in the count.

Check whether the count is divisible by 2,

if yes, then even++

import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter number of elements of array");
        int n = input.nextInt();

        // Initializing an array of size n
        int[] arr = new int[n];

        // Enter elements of array
        System.out.println("Enter Elements of array");
        for (int i = 0; i < arr.length; i++) {
            arr[i] = input.nextInt();
        }

        // Initializing integer which will store number of Elements containing even
        // number digits inside array
        int ans = even(arr);

        // Printing ans
        System.out.println("Elements containing even number digits inside array " + ans);

        input.close();

    }

    static int even(int[] arr) {
        int even = 0;
        for (int i = 0; i < arr.length; i++) {
            int count = 0;
            int temp = arr[i];
            while (temp != 0) {
                count++;
                temp /= 10;
            }
            if (count % 2 == 0) {
                even++;
            }
        }
        return even;

    }
}

Output: