アルゴリズム_にぶんたんさく
1121 ワード
分割検索(折り返し検索)ぶんかつけんさく
package com.xwl;
/**
*
* @author Administrator
*/
public class Test_erfenchazhao {
public static void main(String[] args) {
//
int[] arr = new int[] {12,13,25,64,87};
System.out.println(search(arr, 12));
System.out.println(search(arr, 13));
System.out.println(search(arr, 25));
}
// key
public static int search(int[] arr, int key) {
// start
int start = 0;
// end
int end = arr.length - 1;
//
while (start <= end) {
//
int middle = (start + end) / 2;
// key -1 end
if (key < arr[middle]) {
end = middle - 1;
} else if (key > arr[middle]) {
// = +1
start = middle + 1;
} else {
return middle;
}
}
return -1;
}
}