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

Commit d918589

Browse files
Add binary search code
1 parent 9d62828 commit d918589

File tree

2 files changed

+26
-18
lines changed

2 files changed

+26
-18
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package algorithm.basicMath;
2+
3+
/**
4+
* Created by Jbee on 2017. 6. 5..
5+
*/
6+
public class BasicCombination {
7+
}

‎src/test/java/search/BinarySearchTest.java‎

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -13,36 +13,37 @@ public class BinarySearchTest {
1313
*/
1414
@Test
1515
public void test() {
16-
int[] arr = new int[7];
17-
arr[0] = 52;
18-
arr[1] = 31;
19-
arr[2] = 24;
20-
arr[3] = 45;
21-
arr[4] = 13;
22-
arr[5] = 11;
23-
arr[6] = 28;
24-
assertThat(searchByRec(arr, 24), is(2));
25-
assertThat(search(arr, 24), is(2));
16+
int[] arr1 = {11,22,33,44,55,66,77,88};
17+
int[] arr2 = {11,22,33,44,55,66,77};
18+
int[] arr3 = {1};
19+
int[] arr4 = {};
20+
assertThat(search(arr1, 33), is(2));
21+
assertThat(search(arr2, 22), is(1));
22+
assertThat(search(arr3, 1), is(0));
23+
assertThat(search(arr4, 1), is(-1));
24+
25+
assertThat(searchByRec(arr1, 33), is(2));
26+
assertThat(searchByRec(arr2, 22), is(1));
27+
assertThat(searchByRec(arr3, 1), is(0));
28+
assertThat(searchByRec(arr4, 1), is(-1));
2629
}
2730

2831
// while version
2932
private int search(int[] arr, int target) {
3033
if (arr == null) return -1;
3134
int left = 0;
3235
int right = arr.length - 1;
33-
36+
intmid;
3437
while (left <= right) {
35-
intmid = left + (right - left) / 2;
38+
mid = left + (right - left) / 2;
3639
if (arr[mid] == target) {
3740
return mid;
3841
}
3942

4043
if (arr[mid] < target) {
41-
left = mid;
42-
right -= 1;
44+
left = mid + 1;
4345
} else {
44-
right = mid;
45-
left += 1;
46+
right = mid - 1;
4647
}
4748
}
4849
return -1;
@@ -61,9 +62,9 @@ private int searchRec(int[] arr, int left, int right, int target) {
6162
if (arr[mid] == target) {
6263
return mid;
6364
} else if (arr[mid] < target) {
64-
return searchRec(arr, mid, right - 1, target);
65+
return searchRec(arr, mid + 1, right, target);
6566
} else {
66-
return searchRec(arr, left + 1, mid, target);
67+
return searchRec(arr, left, mid - 1, target);
6768
}
6869
}
6970
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /