利用传统数组的方法
public static int chuan(int a[], int x) {
int i;
for (i = 0; i < a.length; i++) {
if (a[i] == x) {
return i;
}
}
return -1;
}
非递归二分查找
public static int binarySearch(int a[], int x, int n) {
if (x < a[0] && x > a[a.length - 1]) {
int left = 0;
int right = n - 1;
while (left <= right) {
int middle = (left + right) / 2;
if (x == a[middle]) {
return middle;
}
if (x > a[middle]) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return -1;
}
return -1;
}
递归算法
public static int binarySearch(int a[], int x, int left, int right) {
if (x < a[0] && x > a[a.length - 1]) {
if (left > right) {
return -1;//
} else {
int mid = (left + right) / 2;
if (x == a[mid]) {
return mid;
}
if (x > a[mid]) {
return binarySearch(a, x, mid + 1, right);
} else {
return binarySearch(a, x, left, mid);
}
}
}
return -1;
}
整体代码
package 练习;
import java.util.Scanner;
public class 二分搜索技术 {
//传统数组的方法
public static int chuan(int a[], int x) {
int i;
for (i = 0; i < a.length; i++) {
if (a[i] == x) {
return i;
}
}
return -1;
}
//非递归二分查找
public static int binarySearch(int a[], int x, int n) {
if (x < a[0] && x > a[a.length - 1]) {
int left = 0;
int right = n - 1;
while (left <= right) {
int middle = (left + right) / 2;
if (x == a[middle]) {
return middle;
}
if (x > a[middle]) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return -1;
}
return -1;
}
// 递归算法
public static int binarySearch(int a[], int x, int left, int right) {
if (x < a[0] && x > a[a.length - 1]) {
if (left > right) {
return -1;//
} else {
int mid = (left + right) / 2;
if (x == a[mid]) {
return mid;
}
if (x > a[mid]) {
return binarySearch(a, x, mid + 1, right);
} else {
return binarySearch(a, x, left, mid);
}
}
}
return -1;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入数组的数");
int a[];
a = new int[5];
for (int i = 0; i < a.length; i++) {
a[i] = in.nextInt();
}
System.out.println("你要查找的数");
int n = a.length + 1;
int x = in.nextInt();
int left = 0;
int right = a.length;
System.out.println("传统的方法");
System.out.println(chuan(a, x));
System.out.println("非递归二分查找");
System.out.println(binarySearch(a, x, n));
System.out.println("递归二分查找");
System.out.println(binarySearch(a, x, left, right));
}
}
输入数据:5.4.3.2.1
运行结果: