This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| algorithm [2015/12/27 12:15] – [이진 탐색 (Binary Search)] ledyx | algorithm [2021/02/07 03:15] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | = Algorithm = | + | ~~REDIRECT>algorithm:algorithm~~ |
| - | + | ||
| - | {{tag>Algorithm}} | + | |
| - | + | ||
| - | = 마방진 (Magic Square) = | + | |
| - | * 홀수만 처리 가능! | + | |
| - | <sxh java ; title:Language : Java> | + | |
| - | int size = 5; | + | |
| - | + | ||
| - | int[][] arr = new int[size][size]; | + | |
| - | + | ||
| - | int middle = size/2; | + | |
| - | + | ||
| - | int i=0, j=middle; | + | |
| - | for(int num=1 ; num< | + | |
| - | arr[i][j] = num; | + | |
| - | + | ||
| - | //행 감소 | + | |
| - | i--; | + | |
| - | if(i < 0) | + | |
| - | i = size-1; | + | |
| - | + | ||
| - | //열 증가 | + | |
| - | j = (++j)%size; | + | |
| - | //아래 표현과 같다. | + | |
| - | /*j++; | + | |
| - | if(j >= size) | + | |
| - | j = 0;*/ | + | |
| - | + | ||
| - | // | + | |
| - | if(num%size == 0) { | + | |
| - | i = (i+2)%size; | + | |
| - | j--; | + | |
| - | if(j < 0) | + | |
| - | j = size-1; | + | |
| - | } | + | |
| - | } | + | |
| - | </ | + | |
| - | + | ||
| - | = 합병 정렬 (Merge Sort) = | + | |
| - | [[Merge Sort]] | + | |
| - | + | ||
| - | = 이진 탐색 (Binary Search) = | + | |
| - | * A < X ≤ B 조건을 검색. | + | |
| - | <sxh java> | + | |
| - | // A < X <= B | + | |
| - | public static int binarySearch(int[] arr, int target) { | + | |
| - | if(arr[arr.length - 1] < target) | + | |
| - | return arr.length - 1; | + | |
| - | + | ||
| - | int left = 0; | + | |
| - | int right = arr.length; | + | |
| - | + | ||
| - | int result = -1; | + | |
| - | + | ||
| - | while (left <= right) { | + | |
| - | int mid = (left + right) / 2; | + | |
| - | + | ||
| - | if (mid > 0) { | + | |
| - | + | ||
| - | int limit = arr[mid]; | + | |
| - | + | ||
| - | if (arr[mid - 1] <= target && target <= limit) { | + | |
| - | + | ||
| - | //A < X <= B | + | |
| - | if(arr[mid] == target) { | + | |
| - | + | ||
| - | if(mid >= arr.length - 1) { | + | |
| - | result = mid; | + | |
| - | } | + | |
| - | else { | + | |
| - | result = mid + 1; | + | |
| - | } | + | |
| - | } | + | |
| - | else | + | |
| - | result = mid; | + | |
| - | + | ||
| - | + | ||
| - | break; | + | |
| - | } | + | |
| - | else if(target > limit) | + | |
| - | left = mid + 1; | + | |
| - | else if(target < limit) | + | |
| - | right = mid - 1; | + | |
| - | + | ||
| - | } | + | |
| - | else { | + | |
| - | // | + | |
| - | result = 0; | + | |
| - | break; | + | |
| - | } | + | |
| - | } | + | |
| - | + | ||
| - | return result; | + | |
| - | } | + | |
| - | </ | + | |