class ArrayDemo6
{
public static void main(String args[])
{
int[] arr={1,4,6,9,12,23};
int index=getIndex(arr,6);
System.out.println(index);
}
public static int getIndex(int[] arr,int key)
{
int min=0;
int max=arr.length-1;
int mid=(min+max)/2;
while(arr[mid]!=key)
{
if(key>arr[mid])
min=mid+1;
else if(key<arr[mid])
max=mid-1;
if(max<min)
return -1;
mid=(min+max)/2;
}
return mid;
}
}
class ArrayDemo6_1
{
public static void main(String []args)
{
int[] arr={1,4,6,9,12,23};
int index=getIndex(arr,23);
System.out.println(index);
}
public static int getIndex(int[] arr,int key)
{
int min=0;
int max=arr.length-1;
while(min<=max)
{
int mid=(min+max)>>1;
if(key>arr[mid])
min=mid+1;
else if(key<arr[mid])
max=mid-1;
else
return mid;
}
return -1;
}
}
|
|