Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void main(String[] args) {
- int data[] = {9, 15, 32, 71, 78, 92, 101, 115, 117, 129, 270, 350, 470, 500};
- int pos = binarySearch(data, 128);
- System.out.println("position 128 at : " + pos);
- pos = binarySearch(data, 117);
- System.out.print("found 117 at : " + pos);
- }
- private static int binarySearch(int[] data, int key) {
- int position = -1;
- int left = 0;
- int right = data.length - 1;
- int mid = 0;
- while (left <= right) {
- mid = (left + right) / 2;
- if (key > data[mid]) {
- left = mid + 1;
- } else if (key < data[mid]) {
- right = mid - 1;
- } else {
- position = mid;
- break;
- }
- }
- return position; //return index ของ array ที่หาเจอ ถ้าไม่เจอ return -1
- }
- private static int binarySearch(Comparable[] data, Comparable key) {
- int position = 0;
- return position; //return index ของ array ที่หาเจอ ถ้าไม่เจอ return -1
- }
Add Comment
Please, Sign In to add comment