Skip to content

Instantly share code, notes, and snippets.

@devetude
Last active September 22, 2016 14:49
Show Gist options
  • Save devetude/5519cc7c0231d87454a019caaa541391 to your computer and use it in GitHub Desktop.
Save devetude/5519cc7c0231d87454a019caaa541391 to your computer and use it in GitHub Desktop.
이진탐색 알고리즘 (Binary Search)
/**
* 이진탐색 알고리즘 (Binary Search)
*
* @author devetue
*/
public class Main {
public static void main(String args[]) {
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int key = 7;
int start = 0;
int end = numbers.length - 1;
int res = -1;
while (start <= end) {
int middle = (start + end) / 2;
if (numbers[middle] < key) {
start = middle + 1;
}
else if (numbers[middle] > key) {
end = middle - 1;
}
else {
res = middle;
break;
}
}
if (res == -1) {
System.out.println("There isn't key here.");
}
else {
System.out.println("key's index is " + res + ".");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment