JAvaの二分検索
3097 ワード
二分検索の前提条件は、配列内の要素が昇順であれ降順であれ並べ替えられていることです.サンプルコードは次のとおりです.
//
import java.util.*;
public class Demo032605{
public static int binarySearch( int[] list, int number ){
int low = 0;
int high = list.length-1;
while ( high >= low ){
int mid = ( low + high ) / 2;
if ( number > list[mid] )
low = mid + 1;
else if ( number == list[mid] )
return mid;
else
high = mid - 1;
}
return -1;
}
public static void main( String [] args ){
int[] list = { 2, 4, 5, 6, 11, 12,45,66,88,87,90,99,233 };
for ( int i = 0; i < list.length; i++ ){
System.out.print( list[i] + "\t" );
}
System.out.println( "
" );
Scanner input = new Scanner( System.in );
System.out.print( "please input a number: " );
int number = input.nextInt();
int k = binarySearch( list, number );
System.out.println( "The " + number + " list is " + k );
}
}