Last active
November 14, 2017 08:25
-
-
Save an-sangkil/974a180d550b5fe609b0aaefb1e9ed43 to your computer and use it in GitHub Desktop.
이진탐색 알고리즘
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.knkcorp.justget.test; | |
import java.util.Arrays; | |
import org.junit.Test; | |
/** | |
* Description : | |
* | |
* @author : skan. | |
* @version : | |
* <p> | |
* Copyright (C) 2017 Skan Corp. All right reserved. | |
* @since : 2017-11-14. | |
*/ | |
public class BinarySearch { | |
/** | |
* 오름차순으로 정렬 후 조회 | |
* @throws Exception | |
*/ | |
@Test | |
public void search() throws Exception { | |
int[] number = new int[]{22,21,23,1,2,3,4,5,6,7}; | |
// 오름차순 정렬 | |
Arrays.sort(number); | |
// 정렬 내용 확인 | |
Arrays.stream(number).forEach(i-> System.out.println(i)); | |
int target = 22; | |
int head = 0; | |
int tail = number.length-1; | |
int index = 0; | |
boolean isFind = false; | |
// 반복문 실행 | |
while (tail >= head) { | |
// 가운데 인덱스 | |
int mid = (head+tail)/2; | |
// 값이 일치하면 찾아서 적용 | |
if(number[mid] == target) { | |
System.out.println("찾았당" + number[mid] + "[" + mid + "] index = " + index); | |
isFind = true; | |
break; | |
} | |
// 타겟값이 검색된 값보다 크면 head 값을 mid+1 | |
if(target >= number[mid] ) { | |
head = mid+1; | |
} | |
// 타켓 값이 겁색된 값보다 작으면 tail 값을 mid-1; | |
else { | |
tail = mid-1; | |
} | |
index ++; | |
} | |
if(!isFind) { | |
throw new Exception("일치하는 값이 없습니다."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment