Java
Search Algorithms are the methods of searching a particular element from a list of elements as well as finding their position in that list. These algorithms are classified into two types based on the way of performing searches as described below :
It is the simplest search algorithm for searching a particular element from a list. Steps to be performed :
You can use this algorithm for both integers as well as string elements you need to search in the list.
Program for Integer Array :
public class LinearSearch {
public static void main(String[] args) {
int arr[]= {5,23,40,17,3,19,10}; //Array declaration
int element=10; //Element to be searched
int flag=0;
for(int i=0; i<arr.length;i++) { //Iterating elements of the array
if(arr[i]==element) {
System.out.println("Element is present at "+i+" index position");
flag=flag+1;
}
}
if(flag==0){
System.out.println("Searched Element not present in the list");
}
}
}
Program for String Array :
public class LinearSearch {
public static void main(String[] args) {
String[] arr= {"roshni", "deepak", "rohan", "shivani"}; //Array declaration for string
String element="rohan"; //String to be searched
int flag=0;
for(int i=0; i<arr.length;i++) { //Iterating elements of the array
if(arr[i].equals(element)){
System.out.println("Item present in "+i+" index position");
flag=flag+1;
}
}
if(flag==0) {
System.out.println("Item not found in the list");
}
}
}
This algorithm is based on the technique of divide and conquer which means it first divides the array in two halves. Then starts searching for a particular element in that sorted array. This process is repeated until it finds the element. Steps to be performed :
NOTE : Binary Search is always applied to the sorted data, so make sure you perform it only to the list of sorted data elements.
Program :
public class BinarySearch {
public static void main(String[] args) {
int arr[]= {3,12,6,5,7,8,10,15};
int element=7; //Element to be searched
int left=0;
int right=arr.length-1;
int middle=(left+right)/2;
while(left<=right){ //Iterating elements
if(arr[middle]==element){
System.out.println("Element is at "+middle+ " index position");
break;
}else if(arr[middle]<element){
left=middle+1;
}else{
right=middle-1;
}middle=(left+right)/2;
}
if(left>right){
System.out.println("Element not found");
}
}
}
We are an Web development company that provides complete enterprise solutions with focus on building custom software applications. Our 360-degree Web development services enable organizations to streamline their business processes, enhance productivity, and improve operational efficiency. For more information, contact us at [email protected].