用java实现,通过键盘输入一个数,在排序后的数组中,采用折半查找法查找该数在数组中的 位置。

通过键盘输入一个数,在排序后的数组中,采用折半查找法查找该数在数组中的
位置。如果查找到该数,输出信息:XXX:Y。其中XXX代表待查找数,Y代表该数在数组中的位置

import java.util.Scanner;

public class Test {
static int bsearch( int[] a, int v ) {
int l, r;
l = 0; r = a.length-1;
while ( l <= r ) {
int m = (l+r)/2;
if ( a[m] == v ) return m; else
if ( a[m] > v ) r = m-1; else
if ( a[m] < v ) l = m+1;
}
return -1;
}

public static void main( String[] args ) {
int[] a = { 1,3,5,7,9 };
Scanner sc = new Scanner(System.in);
System.out.println("请输入您要找的值:");
int num = sc.nextInt();
System.out.println( "找到 " + num + " 在数组的位置是:" + bsearch( a, num ) );
}
}追问

不能自己输入数码

追答

你说的是那个数组吗,现在是可以自己输入要查找的数据啊

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-11-14
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class TestSearch {

public static int findIndex(int[] array, int key) {
return Arrays.binarySearch(array, key);
}

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[] { 3, 4, 5, 6, -23, 565, 56, 5, 78, 8, 8, 8, 12 };
// sorted
Arrays.sort(arr);

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入:");
try {
String key_str = br.readLine();
int key = Integer.parseInt(key_str);
int index = findIndex(arr, key);

if (index > 0) {
System.out.println(key + ":" + index);
} else {
System.out.println(key + ": not found!");
}

} catch (IOException e1) {
e1.printStackTrace();
}

}

}
第2个回答  2014-11-14
so easy 呀