Skip to content

Instantly share code, notes, and snippets.

@mizushou
Last active November 9, 2017 03:22
Show Gist options
  • Save mizushou/f895661c9e62181257a5514a4fbe5789 to your computer and use it in GitHub Desktop.
Save mizushou/f895661c9e62181257a5514a4fbe5789 to your computer and use it in GitHub Desktop.
* 二分木探索(バイナリサーチ)
import java.util.Scanner;
class BinarySearch2 {
static int binarySearch(int[] A, int key) {
int left = 0;
int right = A.length;
while(left < right) {
int mid = (left + right)/2;
if(A[mid] == key) {
return mid;
} if(key < A[mid]) {
right = mid;
} else {
left = mid;
}
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int key = sc.nextInt();
int[] A = new int[n];
for(int i=0; i<n; i++){
A[i] = sc.nextInt();
};
sc.close();
System.out.println("keyの位置は : " + binarySearch(A, key));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment