Skip to content

Commit c057811

Browse files
Binary search algorithm added
1 parent 367788e commit c057811

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/search/BinarySearch.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package search;
2+
3+
import java.util.Scanner;
4+
5+
public class BinarySearch {
6+
public static void main(String[] args) {
7+
Scanner input = new Scanner(System.in);
8+
System.out.println("Size of elements");
9+
int N = input.nextInt();
10+
11+
int[] inputArr = new int[N];
12+
13+
for (int i = 0; i < N; i++) {
14+
System.out.println("Array["+i+"] :");
15+
inputArr[i]= input.nextInt();
16+
}
17+
18+
System.out.println("Enter the element which you want to search:");
19+
int searchElement = input.nextInt();
20+
System.out.println("Output");
21+
System.out.println("index : "+ binarySearch(inputArr,searchElement));
22+
}
23+
24+
private static int binarySearch(int[] inputArr, int searchElement) {
25+
26+
int first=0;
27+
int last = inputArr.length - 1;
28+
29+
while(first<=last){
30+
int mid = (first + last)/2;
31+
if(searchElement==inputArr[mid]){
32+
return mid;
33+
}
34+
if(searchElement< inputArr[mid]){
35+
last = mid-1;
36+
}else{
37+
first = mid + 1;
38+
}
39+
}
40+
return -1;
41+
}
42+
}

0 commit comments

Comments
 (0)