Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitcea1eac

Browse files
InterviewQuestions/src/package1/BinarySearch.java
1 parente568808 commitcea1eac

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
packagepackage1;
2+
//Given a sorted array and a target, return the index of the target in this array, return -1 if not found.
3+
publicclassBinarySearch {
4+
5+
6+
//if not found in array, return -1;
7+
publicstaticintbinarySearch(int[]nums,inttarget){
8+
if(nums ==null ||nums.length ==0)return -1;
9+
10+
intleft =0,right =nums.length-1;
11+
if(nums[right] <target ||nums[left] >target)return -1;
12+
13+
while(left+1 <right){
14+
intmid =left + (right-left)/2;
15+
if(nums[mid] ==target)returnmid;
16+
elseif(nums[mid] >target){
17+
right =mid;
18+
}else {
19+
left =mid;
20+
}
21+
}
22+
if(nums[left] ==target)returnleft;
23+
elseif(nums[right] ==target)returnright;
24+
return -1;
25+
}
26+
27+
publicstaticvoidmain(String...strings){
28+
29+
30+
31+
//test case 1:
32+
int[]nums =newint[]{1,2,3,4,5,6,7,8,9};//lenght = 9, 9/2 = 4
33+
//int target = 7;
34+
35+
//test case 2:
36+
//int target = 10;
37+
38+
//test case 3:
39+
//int target = -2;
40+
41+
//int target = 1;
42+
inttarget =9;
43+
44+
System.out.println(binarySearch(nums,target));
45+
46+
}
47+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp