62,568
社区成员




package TestErfenCha;
public class TestErfenCha {
public static void search(double shu, double[] arr){
int len = arr.length-1;
int min = 0, max = len, mid = (max-min)/2;
int count = 1;
System.out.println("第"+count+"次的最小值是:"+arr[min]);
System.out.println("第"+count+"次的中间是:"+arr[mid]);
System.out.println("第"+count+"次的最大值是:"+arr[max]);
count++;
while(shu!=arr[mid]){
if(shu>arr[max]){
System.out.println("对不起,数不存在");
break;
}
if(shu<arr[mid]){
min = min;
max = mid-1;
mid = min+(max-min)/2;
System.out.println("第"+count+"次的最小值是:"+arr[min]);
System.out.println("第"+count+"次的中间是:"+arr[mid]);
System.out.println("第"+count+"次的最大值是:"+arr[max]);
if(mid<min){
System.out.println("对不起,没有找到");
break;
}
}
else if(shu>arr[mid]){
min = mid+1;
max = max;
mid = min+(max-min)/2;
System.out.println("第"+count+"次的最小值是:"+arr[min]);
System.out.println("第"+count+"次的中间是:"+arr[mid]);
System.out.println("第"+count+"次的最大值是:"+arr[max]);
if(mid<min){
System.out.println("对不起,没有找到");
break;
}
}
if(shu==arr[mid]){
System.out.println("恭喜你找到元素");
break;
}
count++;
}
}
public static void main(String[] args){
double arr[] = new double[15];
for(int i=0;i<15;i++){
arr[i] = i+3;
System.out.print(arr[i]+" ");
}
System.out.println();
search(7.69,arr);
}
}
public class BinarySearch
{
public static final int NOT_FOUND = -1;
/**
* Performs the standard binary search
* using two comparisons per level.
* @return index where item is found, or NOT_FOUND.
*/
public static <AnyType extends Comparable<? super AnyType>>
int binarySearch( AnyType [ ] a, AnyType x )
{
int low = 0;
int high = a.length - 1;
int mid;
while( low <= high )
{
mid = ( low + high ) / 2;
if( a[ mid ].compareTo( x ) < 0 )
low = mid + 1;
else if( a[ mid ].compareTo( x ) > 0 )
high = mid - 1;
else
return mid;
}
return NOT_FOUND; // NOT_FOUND = -1
}
// Test program
public static void main( String [ ] args )
{
int SIZE = 8;
Integer [ ] a = new Integer [ SIZE ];
for( int i = 0; i < SIZE; i++ )
a[ i ] = i * 2;
for( int i = 0; i < SIZE * 2; i++ )
System.out.println( "Found " + i + " at " +
binarySearch( a, i ) );
}
}
System.out.println("恭喜您做对了");