class ArrayTest5
{
public static void main(String[] args)
{
int [] arr={1,12,5,8,12,90};
int index=getIndex(arr,20);
System.out.println("index="+index);
}
public static int halfSearch(int [] arr,int key)
{
int min,max,mid;
min =0;
max =arr.length-1;
mid=(max+min)/2;
while (arr[mid]!=key)
{
if(key>arr[mid])
min =mid+1;
else (key<arr[mid])
max=mid-1;
mid=(max+min)/2;
}
return mid;
}
public static int getIndex(int [] arr, int key)
{
for (int x=0;x<arr.length;x++ )
{
if (arr[x]=key)
return x;
class ArrayTest5
{
public static void main(String[] args)
{
int [] arr={1,12,5,8,12,90}; //顺便说一句,折半查找是对有序数组进行查找的,你这里的数组是无序的
int index=getIndex(arr,20);
System.out.println("index="+index);
}
public static int halfSearch(int [] arr,int key)
{
int min,max,mid;
min =0;
max =arr.length-1;
mid=(max+min)/2;
while (arr[mid]!=key)
{
if(key>arr[mid])
min =mid+1;
else (key<arr[mid]) //这里是语法错误,else是不带条件判断的,要用的话,应该改为else if(),这里可以不用判断,直接else max=mid-1;
max=mid-1;
mid=(max+min)/2;
}
return mid;
}
public static int getIndex(int [] arr, int key)
{
for (int x=0;x<arr.length;x++ )
{
if (arr[x]=key) //这里写错了,应该是arr[x]==key
return x;
作者: 黑马-王建雨 时间: 2012-5-12 11:15
class ArrayTest5
{
public static void main(String[] args)
{
int [] arr={1,12,5,8,12,90};
int index=getIndex(arr,20);
System.out.println("index="+index);
}
public static int halfSearch(int [] arr,int key)
{
int min,max,mid;
min =0;
max =arr.length-1;
mid=(max+min)/2;
while (arr[mid]!=key)
{
if(key>arr[mid])
min =mid+1;
else (key<arr[mid])//少了个if
max=mid-1;
mid=(max+min)/2;
}
return mid;
}
public static int getIndex(int [] arr, int key)
{
for (int x=0;x<arr.length;x++ )
{
if (arr[x]=key)
return x;
}
return -1;
}
} 作者: 李啸 时间: 2012-5-12 12:15
public static void main(String[] args)
{
int [] arr={1,12,5,8,12,90};
int index=getIndex(arr,20);
System.out.println("index="+index);
}
public static int halfSearch(int [] arr,int key)
{
int min,max,mid;
min =0;
max =arr.length-1;
mid=(max+min)/2;
while (arr[mid]!=key)
{
if(key>arr[mid])
min =mid+1;
else if(key<arr[mid])
max=mid-1;
mid=(max+min)/2;
}
return mid;
}
public static int getIndex(int [] arr, int key)
{
for (int x=0;x<arr.length;x++ )
{
if (arr[x]==key)
return x;