|
1 | 1 | package search; |
2 | 2 |
|
3 | | -/** |
4 | | - * Created by Jbee on 2017. 6. 1.. |
5 | | - */ |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import static org.hamcrest.CoreMatchers.is; |
| 6 | +import static org.junit.Assert.assertThat; |
| 7 | + |
6 | 8 | public class BinarySearchTest { |
| 9 | + |
| 10 | + /* |
| 11 | + TASK |
| 12 | + binary search를 사용하여 O(log n)의 시간복잡도로 target을 찾는다. |
| 13 | + */ |
| 14 | + @Test |
| 15 | + 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)); |
| 26 | + } |
| 27 | + |
| 28 | + // while version |
| 29 | + private int search(int[] arr, int target) { |
| 30 | + if (arr == null) return -1; |
| 31 | + int left = 0; |
| 32 | + int right = arr.length - 1; |
| 33 | + |
| 34 | + while (left <= right) { |
| 35 | + int mid = left + (right - left) / 2; |
| 36 | + if (arr[mid] == target) { |
| 37 | + return mid; |
| 38 | + } |
| 39 | + |
| 40 | + if (arr[mid] < target) { |
| 41 | + left = mid; |
| 42 | + right -= 1; |
| 43 | + } else { |
| 44 | + right = mid; |
| 45 | + left += 1; |
| 46 | + } |
| 47 | + } |
| 48 | + return -1; |
| 49 | + } |
| 50 | + |
| 51 | + //recursive version |
| 52 | + private int searchByRec(int[] arr, int target) { |
| 53 | + if (arr == null) return -1; |
| 54 | + return searchRec(arr, 0, arr.length - 1, target); |
| 55 | + } |
| 56 | + |
| 57 | + private int searchRec(int[] arr, int left, int right, int target) { |
| 58 | + if (left > right || left < 0 || right >= arr.length) return -1; |
| 59 | + int mid = left + (right - left) / 2; |
| 60 | + |
| 61 | + if (arr[mid] == target) { |
| 62 | + return mid; |
| 63 | + } else if (arr[mid] < target) { |
| 64 | + return searchRec(arr, mid, right - 1, target); |
| 65 | + } else { |
| 66 | + return searchRec(arr, left + 1, mid, target); |
| 67 | + } |
| 68 | + } |
7 | 69 | } |
0 commit comments