public class Test1 { private static final Logger log = LoggerFactory.getLogger(com.xpfirst.hdrRouter.Test.Test1.class); public static void main(String[] args){ String str = "sl3234ls12123679804jge"; Integer czInt = 6; getIntAndSort(str,czInt); } //取出字符串中的整数放到数组中并排序,查找一个值 public static void getIntAndSort(String str,Integer czInt) { // 取出整数 List<Integer> list = new ArrayList<>(); for(int i = 0; i < str.length(); i++) { String s = str.substring(i,i+1); try{ Integer tmpint = Integer.valueOf(s); list.add(tmpint); } catch(Exception ex){} } // 插入排序 int len = list.size(); for(int i = 1; i < len; i++){ for( int j = i; j>0 && list.get(j-1) > list.get(j); j--){ Integer tmpInt = list.get(j-1); list.set(j-1,list.get(j)); list.set(j,tmpInt); } } // 二分查找 System.out.print(list.toString()); System.out.print(erfen(list,czInt)); } /** * @description 二分查找 * @author 郜金丹 * @date 2019/1/16 13:42 * @return Exception **/ public static int erfen(List<Integer> list,Integer searchInt) { if (list.size() == 0){ return -1; } int mod = list.size()/2; Integer tmpInt = list.get(mod); if (searchInt.equals(tmpInt)){ return mod; } else if (searchInt > tmpInt){ List<Integer> tmpList = list.subList(mod+1,list.size()); return mod +1+ erfen(tmpList,searchInt); } else { List<Integer> tmpList = list.subList(0,mod); return erfen(tmpList,searchInt); } } /** * @description 插入排序 * @date 2019/1/16 11:13 * @return Exception **/ public static void charu(int[] ints) { int len = ints.length; for(int i = 1; i < len; i++) { for (int j = i; j > 0 && ints[j-1] > ints[j]; j--){ int int1 = ints[j-1]; int int2 = ints[j]; ints[j] = int1; ints[j-1] = int2; } } } /** * @description maopao * @date 2019/1/16 10:44 * @param * @return Exception **/ public static void maopao(int[] ints) { int len = ints.length; for(int i = 0; i < len; i++) { for (int j = 1; j < len - i; j++){ int int1 = ints[j-1]; int int2 = ints[j]; if (int1 > int2){ ints[j] = int1; ints[j-1] = int2; } } } } }
一个面试题:取出字符串中的整数放到数组中并排序,查找一个值
最新推荐文章于 2024-10-16 21:32:12 发布