Last active
November 9, 2017 03:22
-
-
Save mizushou/f895661c9e62181257a5514a4fbe5789 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 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