二分查找
public class BinarySearch {
public static void main(String[] args) {
int[] arr={10,38,65,97,76,13,27,49,78,34,12,64,1};
Arrays.sort(arr);
binarySearch(arr,1);
}
public static void binarySearch(int[] arr,int key){
int start=0;int end=arr.length;
while (start<=end){
int mid=(start+end)/2;
if (arr[mid]<key){
start=mid+1;
}
else if(arr[mid]>key){
end=mid-1;
}
else {
System.out.println("找到了,下标为"+mid);
return;
}
}
System.out.println("没找到");
}
}
插值查找
适用场景:目标已经有序而且分布均匀
key为要查找的值
public class InsertSearch {
public static void main(String[] args) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
System.out.println(Arrays.toString(arr));
int i = InsertValue(arr, 0, arr.length-1, 10);
System.out.println(i);
}
/**
*
* @param arr 要比较的数组
* @param start 开始
* @param end 结束
* @param key 要查找的元素
*/
public static int InsertValue(int[] arr, int start, int end, int key){
System.out.println("ccccc");
// 利用拉格朗日订立找到更好的位置
int mid = start+(end - start) * (key - arr[start])/(arr[end] - arr[start]);
// 防止 mid 越界
if (start > end || key>arr[arr.length-1] || key <arr[0] ){
return -1;
}
if (key > arr[mid]){
return InsertValue(arr,mid+1,end,key);
}
else if (key <arr[mid]){
return InsertValue(arr,start,mid -1,key);
}
else {
return mid+1;
}
}
}
斐波那契查找
要求有序
-1因为数组下标从0开始
// 斐波那契查找(黄金分割查找)
public class FSearch {
public static void main(String[] args) {
int[] arr = new int[]{1, 8, 10 , 15, 100, 1234};
System.out.println(search(arr, 15));
}
static int Maxsize = 20;
// 生成一个足够大的斐波那契数组
// 可以发现两个相邻数的比例,无限接近黄金分割值0.618
public static int[] fibonacci(){
int[] f = new int[Maxsize];
f[0] = 1;
f[1] = 1;
for (int i = 2; i < f.length - 1; i++) {
f[i] = f[i -1] +f[i-2];
}
return f;
}
public static int search(int[] arr, int key){
int low = 0;
int high = arr.length - 1;
int mid = 0;
int k = 0;//存放数组下标
int[] f = fibonacci();
// 获取一个接近数组长的分割值
while (high > f[k]){
k++;
}
// 将数组扩容至可以分割,并向末尾添加最后的值
int[] temp = Arrays.copyOf(arr, f[k]);
for (int i = high+1; i < f[k]; i++) {
temp[i] = arr[high];
}
// 开始进行查找
while (low <= high){
mid = low +f[k-1]-1;
if (key < temp[mid]){
high = mid - 1;
// 进入前半部分f[k -1]
k--;
}
else if (key >temp[mid]){
low = mid + 1;
k-=2;
}
else {// 找到
// 数组被扩充过,mid可能大于high,但已经时重复值了
if(mid<high){
return mid;
}
else {
return high;
}
}
}
return -1;
}
}