Skip to content

Commit 0230de5

Browse files
committed
Binary Search
1 parent 2a49e54 commit 0230de5

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

Searching/binarysearch.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.company;
2+
3+
public class binarysearch {
4+
public static void main(String[] args) {
5+
int[] nums={5,6,7,8,10,12,15,17,21,25,29,32,35,36,39,40,45,49,51};
6+
int target= 15;
7+
int ans= binarysearch(nums,target);// passing values into the function
8+
//System.out.println(ans);
9+
if(ans==-1){
10+
System.out.println("Target element not present in given array");//print if element not present in array
11+
}
12+
else {
13+
System.out.println("Taget is present at index: "+ans);//print if element present in array with index
14+
}
15+
}
16+
static int binarysearch(int[] nums, int target) { //declaring function
17+
int Fisrt = 0;//element present at the fisrt position
18+
int last = nums.length - 1;//element present at the last position
19+
while (Fisrt <= last) {
20+
int mid;
21+
mid = Fisrt + (last - Fisrt) / 2;//finding middle element present inside the array
22+
23+
if (target < nums[mid]) {
24+
last = mid - 1;
25+
} else if (target > nums[mid]) {
26+
Fisrt = mid + 1;
27+
} else {
28+
return mid;
29+
}
30+
}
31+
return -1;
32+
}
33+
}

0 commit comments

Comments
 (0)