Skip to content

Instantly share code, notes, and snippets.

@mizushou
Created November 8, 2017 16:36
Show Gist options
  • Save mizushou/bd8143ad066154e37a14bee17c42781b to your computer and use it in GitHub Desktop.
Save mizushou/bd8143ad066154e37a14bee17c42781b to your computer and use it in GitHub Desktop.
import java.util.Scanner;
class BinarySearch {
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