Created
November 8, 2017 16:36
-
-
Save mizushou/bd8143ad066154e37a14bee17c42781b 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
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