-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
51 lines (48 loc) · 1.56 KB
/
BinarySearch.java
File metadata and controls
51 lines (48 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Program: Binary Search Using Recursion
// Topic: Recursion and Searching Algorithms
// Description: Implements the Binary Search algorithm recursively to find a target element in a sorted array.
// The method `Search()` divides the array into halves at each step and compares the middle element with the search key.
// Demonstrates recursive function calls, base and recursive conditions, and array traversal for efficient searching.
package recursion;
import java.util.*;
/**
*
* @author Samim
*/
public class BinarySearch {
public static int Search(int high,int low,int search,int a[]){
int mid=(int)((high+low)/2);
if(low>high){
return 0;
}
if(search > a[high]){
return 0;
}
else if(a[mid]<search){
return Search(high,mid+1,search,a);
}
else if(a[mid]>search){
return Search(mid-1,low,search,a);
}
else{
return a[mid];
}
}
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
int ar[]=new int[5];
int s;
System.out.println("Enter Elements :");
for(int i=0;i<ar.length;i++){
ar[i]=sc.nextInt();
}
System.out.println("Enter Search Value :");
s=sc.nextInt();
if(Search(ar.length-1,0,s,ar)==s){
System.out.println("Element Found !");
}
else{
System.out.println("Element Not Found !");
}
}
}