二分查找关键:mid = (high-low)/2
插值查找演变:mid = low+(high-low)/2
需要将1/2变为 ((查找数字-a[mid])/(a[high]-a[low])
package com.chazhao;
import java.util.Arrays;
class shuzu{
int len,mid,low,high;
public shuzu(){
}
int a[] = new int[100];
public void create(int []temp){
System.out.println("创建数组为:");
System.out.print(a[0]+" ");
for (int i = 1;i<=10;i++){
a[i] = temp[i-1];
System.out.print(a[i]+" ");
}
System.out.println();
}
public void sort(){
Arrays.sort(a,0,10);
System.out.println("排序后为:");
for (int i = 0;i<len+1;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
public void erfen(int key){
System.out.println("这里是二分查找:");
low = 1;
high = len;
while (low<=high){
mid = (low+high)/2;
if (key<a[mid]){
System.out.println("此时mid为:"+mid);
high = mid-1;
}else if (key>a[mid]){
System.out.println("此时mid为:"+mid);
low = mid+1;
}else {
System.out.println("查找完毕,此时mid为:"+mid);
return ;
}
}
}
public void chazhi(int key){
System.out.println("这里是插值查找:");
low = 1;
high = len;
while (low<=high){
mid = low + (high-low)*(key-a[low])/(a[high]-a[low]);
//System.out.println(mid);
if (key<a[mid]){
System.out.println("此时mid为:"+mid);
high = mid-1;
}else if (key>a[mid]){
System.out.println("此时mid为:"+mid);
low = mid+1;
}else {
System.out.println("查找完毕,此时mid为:"+mid);
return ;
}
}
}
}
public class paixu {
public static void main(String[] args) {
// TODO Auto-generated method stub
shuzu px = new shuzu();
int t[] = {10,20,30,40,50,11,22,33,44,55};
px.len = 10;
px.create(t);
px.sort();
px.erfen(40);
px.chazhi(40);
}
}