/*面试题:
* 给定一个有序的数组,如果往该组中储存一个新的元素,并且还是 有序的,那么这个元素的角标如何获取.
*
*/
public class Resarch {
//二分算法折半查找法
public static int halfserach(int a[], int key)
{ int mid;
int min =0;int max =a.length-1;
while(min<=max)
{
mid =(max+min)>>1;//右移一位就等于除以2>>1=/2
if(key>a[mid] )
{
min =mid+1;
}
else if(key<a[mid])
{
max=mid-1;
}
else return mid;
}
return -1;
}
//有序查找
public static int halfser(int a [],int key)
{
int MIN =0;
int MAX =a.length-1;
int MID =(MIN+MAX)/2;
while(key!=a[MID])
{
if(key>a[MID])
{
MIN = MID+1;
}
else if(key<a[MID])
{
MAX=MID-1;
}
if(MAX<MIN)
{
return -1;
}
MID=(MAX+MIN)/2;
}
return MID;
}
//普通查找无序查找
public static int getIndex(int [] a,int key)
{
for(int x=0;x<a.length;x++)
{
if(a[x]==key)
{
return x;
}
}
return -1;
}
public static void main(String [] args)
{
int [] a ={1,5,8,9,28,36,65,71,83,109};
int index= halfser(a, 45);
int M=getIndex(a,10);
int N=halfserach(a,28);
int index1 =Arrays.binarySearch(a, 36);//系统自带折半
System.out.println("index1="+index1);
System.out.println("index="+index);
System.out.println("index="+M);
System.out.println("index="+N);
}
//数组常见功能查找
}