3. Linear Search
Linear Search in Java is a searching algorithm that is used to find the index
of the desired element in an array. It is the simplest and most basic searching
algorithm. In this algorithm, we sequentially visit each element of an array until
the target element is found.
4. Implementation of linear search
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]= {1,3,4,6,8};
int key=4;
for(int i=0;i<arr.length;i++) {
if(arr[i]==key) {
System.out.println(i);
}
}
5.
6. Binary Search Algorithm
Binary Search in Java is a search algorithm that finds the
position of a target value within a sorted array. Binary
search compares the target value to the middle element of
the array. It works only on a sorted set of elements
7. Implementation of binary search
public class Binary_Search {
void binarySearch(int arr[], int key) {
int first=0;
int last=arr.length-1;
while(first<=last) {
int mid=(first+last)/2;
if(arr[mid]==key) {
System.out.println("Element present at index: "+mid);
break;
}
else if(arr[mid]<key) {
first=mid+1;
}
else {
last=mid-1;
}
}
}
public static void main(String[] args) {
int arr[]= {12,2,35,62,85,24,98,63};
int key=24;
Arrays.sort(arr);
for(int i=0;i<arr.length;i++) {
System.out.println(arr[i]+ " ");
}
Binary_Search ob=new Binary_Search();
ob.binarySearch(arr,key);
}
}