/*
折半查找数组中是否有4
{1,4,7,3,8,9,0,4,2}
*/
class HalfSearch
{
public static void arraySort(int[] arr)
{
for (int x = 0;x < arr.length-1 ; x++)
{
for (int y = x+1;y < arr.length ;y++ )
{
if (arr[x] > arr[y])
{
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
}
}
public static int halfSearch(int[] arr,int key)
{
int min = 0,max = arr.length-1,mid;
while (min <= max)
{
mid = (min + max)>>1;
if (key < arr[mid])
{
min = mid +1;
}
else if (key > arr[mid])
{
max = mid -1;
}
else
return min;
}
return -1;
}
public static void main(String[] args)
{
int[] array = {1,4,7,3,8,9,0,4,2};
arraySort(array);
int x = halfSearch(array,9);
if (x != -1 )
{
System.out.println("此值存在于排序后数组中的["+x+"]位置");
}
else
System.out.println("数组中不存在此数");
}
}
到底哪里错了...气死我了 |
|