标签:log ++ exti ack 二分 find tar list code
1 package com.cn.two; 2 3 import java.util.ArrayList; 4 import java.util.Collections; 5 import java.util.List; 6 import java.util.Scanner; 7 8 public class Two { 9 10 //二分法 11 public static int find(List<Integer>list,int num){ 12 int start = 0; 13 int end = list.size()-1; 14 while (start <= end){ 15 int middle = (start + end)/2; 16 if (list.get(middle) == num){ 17 return middle; 18 }else if(list.get(middle) < num){ 19 start = middle + 1; 20 }else{ 21 end = middle - 1; 22 } 23 } 24 return -1; 25 } 26 27 public static void main(String[] args){ 28 List<Integer> list =new ArrayList<Integer>(); 29 Scanner input = new Scanner(System.in); 30 System.out.println("请输入需要查找的一组数字"); 31 String str = input.nextLine(); 32 String[] c = str.split(" "); 33 for(int i = 0 ;i < c.length;i++){ 34 list.add(Integer.valueOf(c[i]));//把字符串数组的内容转成Integer并放入集合 35 } 36 Collections.sort(list); 37 System.out.println(list); 38 System.out.println("请输入需要查找的目标数字"); 39 int num = input.nextInt(); 40 int b = find(list,num); 41 if (b == -1){ 42 System.out.println("没有" + num + "这个数"); 43 }else { 44 System.out.println("找到" + num + "这个数,在" + b + "位置"); 45 } 46 } 47 }
return -1;
}
标签:log ++ exti ack 二分 find tar list code
原文地址:http://www.cnblogs.com/ailsalin/p/6365772.html