Skip to content

Commit 3ccdba1

Browse files
Merge pull request #192 from Kaustubh-git/binarysearch
Binary Search
2 parents ebfb455 + 6692e35 commit 3ccdba1

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

Searching/binarysearch.java

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

0 commit comments

Comments
 (0)