Java-二分查找算法
注释比较详细,直接上代码
package XiaoMi;import java.util.Scanner;public class test9 {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubScanner scan = new Scanner(System.in);String str = scan.nextLine();// System.out.println(str);// 用子串实现-转换为数组int[] n = new int[str.length()];for (int i = 0; i < str.length(); i++) {n[i] = Integer.parseInt(str.substring(i, i + 1)); // 很有用}/** // 暴力遍历,时间复杂度o(n) for(int i=0; in[i+1]) {* System.out.println("最小值为:" + n[i+1]); break; } }*//** int temp =0; for(int i=0,m=(n.length+1)/2; in[b]){ //非顺序 temp = (n.length+1)/2; if(n[temp]>n[b]) { temp =* ()/2; }else{* * } } }*/int num = 1; //要查找的元素int left = 0;int right = n.length - 1;for (int i = 0, m = (n.length + 1) / 2; i < m; i++) {if (n[(left + right) / 2] == num) {System.out.println("位置索引:" + (left + right) / 2);break;}if (n[(left + right) / 2] > num) // 在左边{right = (left + right) / 2;} else {left = (left + right) / 2;}}}public static void search(int m, int n) {}}
运行结果:
123456
位置索引:0
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
