【发布时间】:2018-02-08 18:43:17
【问题描述】:
预期输出:
如果键低于中点
数据:[1, 4, 6, 13, 14, 23, 30, 45, 58, 67, 76, 89, 99]
输入键:6
二分查找:
1 step index - 0 : 1, not found !
2 step index - 1 : 4, not found !
3 step index - 2 : 6, founded !!
如果键大于中点
数据:[1, 4, 6, 13, 14, 23, 30, 45, 58, 67, 76, 89, 99]
输入键:89
二分查找:
1 step index - 0 : 45, not found !
2 step index - 1 : 58, not found !
3 step index - 2 : 67, not found !
4 step index - 3 : 76, not found !
5 step index - 4 : 89, founded !!
我的输出
如果键低于中点
Index- 1 = 4, data founded !
~~ FINISHED SEARCHED ~~
问题是我无法逐步打印过程。帮我完成代码。
如果key大于中点
Index - 10 = 4, data founded !
~~FINISHED SEARCHED~~
来源
这是我的源代码:
package binarysearch;
import java.util.Scanner;
import java.util.Arrays;
public class BinarySearch {
public static void main(String [] args) throws Exception{
Scanner input = new Scanner (System.in);
int[] data = {1, 4, 6, 13, 14, 23, 30, 45, 58, 67, 76, 89, 99};
boolean again = true;
String choose;
while(again == true){
System.out.println("Data : "+Arrays.toString(data));
System.out.print("Input key : ");
int find = input.nextInt();
System.out.println("");
int repeat= 0;
int start= 0;
int end= data.length - 1;
int mid;
while(start <= end){
mid= (start+ end) / 2;
if(find== data[mid]){
break;
}else if(find> data[mid]){
start= mid + 1;
}else{
end= mid- 1;
}
}
if(awal > akhir){
System.out.println("Index - "+start+" = "+find+", data not founded");
}else{
System.out.println("Index - "+start+" = "+find+", data founded !");
}
System.out.println("~~ FINISHED SEARCHED ~~");
System.out.println("");
System.out.print("DO YOU WANT EXIT ? [y] / [x] ? ");
choose= input.next();
if(choose.equals("Y") || choose.equals("y")){
again = true;
}else if(choose.equals("X") || choose.equals("x")){
again= false;
System.exit(0);
System.out.println("SEARCHING IS FINISHED, THANK YOU");
}else{
System.out.println("INVALID INPUT!!");
again= false;
System.exit(0);
}
System.out.println("");
}
}
}
【问题讨论】:
-
这不是二分搜索
标签: java binary-search