Skip to content

Instantly share code, notes, and snippets.

@peter279k

peter279k/JPA05.java

Created May 25, 2017
Embed
What would you like to do?
TQC+ JAVA
import java.util.Scanner;
public class JPA05 {
public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] argv) {
search();
search();
}
public static void search() {
int[] data = {5, 9, 13, 15, 17, 19, 25, 30, 45}; // 已排序資料
System.out.print("請輸入要找尋的資料:");
int target = keyboard.nextInt();
int count = 0;
boolean find = false;
int num = data.length / 2;
while(true) {
count += 1;
if(data[num] == target) {
count -= 1;
find = true;
break;
} else if(data[num] > target) {
int index = 0;
int end = 0;
if(num % 2 == 0) {
end = num * 2;
} else {
end = num * 2 + 1;
}
System.out.println("尋找區間:" + index + "(" + data[index] + ").." + (end) + "(" + data[end] + "),中間:" + num + "(" + data[num] + ")");
if(num-1 < 0) {
break;
}
if(num % 2 == 0) {
num = (num-1) / 2;
} else {
num = num / 2;
}
} else {
int mid = (data.length - 1 - num + 1);
if(mid % 2 == 0) {
mid = (mid-1) / 2;
} else {
mid = mid / 2;
}
if(count == 0) {
System.out.println("尋找區間:" + 0 + "(" + data[0] + ").." + (data.length-1) + "(" + data[data.length-1] + "),中間:" + num + "(" + data[num] + ")");
} else {
System.out.println("尋找區間:" + (num+mid) + "(" + data[num+mid] + ").." + (data.length-1) + "(" + data[data.length-1] + "),中間:" + (num + mid) + "(" + data[num+mid] + ")");
}
if(num + 1 == data.length) {
break;
}
num += 1;
}
}
System.out.println("經過 " + count + " 次的尋找");
if(find) {
System.out.println("您要找的資料在陣列中第" + num + "個位置");
} else {
System.out.println(target + "不在陣列中");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.