import java.io.*; import java.util.*; public class BinarySearch{ public static void main(String[] args) { System.out.println("Start read file..."); int[] origin = readArrayFormTxt("array.txt"); System.out.println("read file completed!"); Arrays.sort(origin); System.out.println("Arrays after sort:"); for (int number : origin) { System.out.println(number); } System.out.println("Pls input the Integer you want find:"); Scanner sc = new Scanner(System.in); int result = binarySearch(sc.nextInt(),origin); System.out.println(result == -1 ? "not found" : "find success,the index is:"+result); } public static int binarySearch(int num, int[] source){ int lo = 0; int hi = source.length - 1; while(lo <= hi){ int mid = lo + (hi - lo) / 2; if(num < source[mid]){ hi = mid - 1; }else if(num > source[mid]){ lo = mid + 1; }else{ return mid; } } return -1; } public static int[] readArrayFormTxt(String filePath){ List<Integer> list = new ArrayList<Integer>(); File file = new File(filePath); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; while ((tempString = reader.readLine()) != null) { list.add(Integer.parseInt(tempString)); } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } int[] array = new int[list.size()]; for ( int i = 0;i<list.size();i++) { array[i] = list.get(i); } return array; } public static void readFileByLines(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { System.out.println(""); reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; while ((tempString = reader.readLine()) != null) { System.out.println("line " + line + ": " + tempString); line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } }
原文:http://www.cnblogs.com/makexu/p/5005409.html