Nothing Special   »   [go: up one dir, main page]

0% found this document useful (0 votes)
127 views1 page

Linear Search

Download as txt, pdf, or txt
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 1

a) Write a program in java to implement the linear search technique.

The input is
an array of length n, according to the user’s choice and the key element to be
found. Print the index values of all the occurrences of the key value.
(2 marks)
Input:
Enter the length of the array
5
Enter the element of the array
1 6 3 7 7
Enter the key value
7
Output:
index - 3 4
SOLUTION:
INPUT:
import java.util.*;
public class LinearSearch {
static void linearsearch()
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter the length of the array");
int a= sc.nextInt();
int[] arr = new int[a];
System.out.println("Enter the elements of the array");
for(int i=0; i<a; i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Enter the key value");
int num=sc.nextInt();
System.out.print("index -");
for(int i=0;i<a;i++)
{
if (arr[i]== num)
System.out.print(" "+ i );
}
}
public static void main(String[] args) {
linearsearch();
}
}

You might also like