Answers for "searching in array in java"

2

how to do a linear searc in java

public static int linear(int[] arr, int keyValue)
{
  int pos = -1; 

    for (int i = 0; i < arr.length; i++)
    {
        if (arr[i] == keyValue)
        {
            pos = i;
            break;
        }
	}
	return pos;
}
Posted by: Guest on April-15-2020
0

search an element in an array java

import java.util.Scanner;
public class Search_Element
{
    public static void main(String[] args) 
    {
        int n, x, flag = 0, i = 0;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter no. of elements you want in array:");
        n = s.nextInt();
        int a[] = new int[n];
        System.out.println("Enter all the elements:");
        for(i = 0; i < n; i++)
        {
            a[i] = s.nextInt();
        }
        System.out.print("Enter the element you want to find:");
        x = s.nextInt();
        for(i = 0; i < n; i++)
        {
            if(a[i] == x)
            {
                flag = 1;
                break;
            }
            else
            {
                flag = 0;
            }
        }
        if(flag == 1)
        {
            System.out.println("Element found at position:"+(i + 1));
        }
        else
        {
            System.out.println("Element not found");
        }
    }
}
Posted by: Guest on May-05-2021

Code answers related to "searching in array in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language