To search an element in array there are two popular algorithms linear search and binary search.
In this tutorial we will learn both ways to perform searching on array.
For Example:
Suppose array arr is [2, 4, 5, 7, 1]
Now we have to search element 4.
So output will be “4 is available at index 1 “
Program 1: Java program to perform search using linear search
- In this program we are taking array size and array element from the users as an input.
- Also we are taking the element that user wanted to search.
- Using for loop we are iterating each array element and matching with the search element.
- If match found than print the array element with index otherwise print “no match found”.
import java.util.*;
public class Main{
public static void main (String[]args){
Scanner sc = new Scanner (System.in);
//taking array size and array element as input
System.out.println ("Enter the size of array1: ");
int size = sc.nextInt();
int arr[] = new int[size];
for (int i = 0; i < size; i++){
System.out.print("Please give value for index " + i + " : ");
arr[i] = sc.nextInt();
}
System.out.print("Please give number you wanted to search ");
int search = sc.nextInt();
//Logic to perform linear search
boolean match=false;
for (int i = 0; i < size; i++){
if(arr[i]==search){
System.out.println("Value is available at index "+ i);
match=true;
break;
}
}
if(match == false){
System.out.println("No search found");
}
}
}
Output
Enter the size of array1:
6
Please give value for index 0 : 2
Please give value for index 1 : 1
Please give value for index 2 : 3
Please give value for index 3 : 4
Please give value for index 4 : 2
Please give value for index 5 : 3
Please give number you wanted to search 4
Value is available at index 3