折半查找的改进

来源:互联网 发布:sap数据导入 编辑:程序博客网 时间:2024/06/05 20:45

本文针对折半查找速度慢的问题,提出了一种三段查找算法,在折半查找的基础上,将搜索区域从两端扩展到三段。

public class LookThree {


private static int index;
private static int[] datas={2,3,7,9,10,34,38,48,56,69,70,81,88,89,101};
public static void main(String[] args) {
long startTime=System.nanoTime();   //获取开始时间  
int x=70;
lookup(x);
System.out.println("index: "+ index);
long endTime=System.nanoTime(); //获取结束时间  
System.out.println("程序运行时间: "+(endTime-startTime)+"ns"); 
}

/**
* 将折半查找分成三段
* @param x
*/
private static void lookup(int x){
int mid1Index; //第一个拆分点
int mid2Index; //第二个拆分点
int leftIndex=0;
int rightIndex=datas.length-1;

while(leftIndex<=rightIndex){
if((rightIndex-leftIndex)<=2){
mid1Index=leftIndex+1*((rightIndex-leftIndex)/2);
mid2Index=leftIndex+2*((rightIndex-leftIndex)/2);
}else{
mid1Index=leftIndex+1*((rightIndex-leftIndex)/3);
mid2Index=leftIndex+2*((rightIndex-leftIndex)/3);
}

if(datas[mid1Index]>x){ //如果第一个拆分点的元素大于目标元素,则将查找范围压缩到第一个区域
rightIndex=mid1Index-1;
}else if(datas[mid1Index]<x && datas[mid2Index]>x){ //压缩到第二个区域
leftIndex=mid1Index+1;
rightIndex=mid2Index-1;
}else if(datas[mid2Index]<x){//压缩到第三个区域
leftIndex=mid2Index+1;
}else if(datas[mid1Index]==x){
index=mid1Index;
return;
}else if(datas[mid2Index]==x){
index=mid2Index;
return;
}
}
}


}
原创粉丝点击