javaarrayslinear-search

I'm new to programming. How do i linear search a number in array, i also have to create a function and pass the array[] and integer through that


public static int[] linearSearch(int arr[], int x) {
        
        for (int i=0; i<arr.length; i++) {
            if (arr[i]==x) {
            return arr;
            }
        }
    }
    
    public static int[] takeInput() {
        Scanner s = new Scanner(System.in);
        int N= s.nextInt();
        int arr[]= new int[N];
        int x=s.nextInt();
        
        for (int i=0; i<N; i++) {
             arr[i]=s.nextInt(); 
        }
        return arr;
    }
        
    
    public static void main(String[] args) {
        
                
    }

I'm unable to pass int x that i've taken as input through takeInput, and also linear search won't accept array and int.


Solution

  • public static int search(int arr[], int x)
        {
            int N = arr.length;
            for (int i = 0; i < N; i++) {
                if (arr[i] == x)
                    return i;
            }
            return -1;
        }
     
        // Driver's code
        public static void main(String args[])
        {
            int arr[] = { 2, 3, 4, 10, 40 };
            int x = 10;
     
            // Function call
            int result = search(arr, x);
            if (result == -1)
                System.out.print(
                    "Element is not present in array");
            else
                System.out.print("Element is present at index "
                                 + result);
        }