二分查找问题(Java版)
1.一般实现
package search;
/** * @author lei 2011-8-17
*/
public class BinarySearch {
/**
* 二分查找
*
* 注意:二分查找只是针对有序排列的各种数组或集合
*
* @param target
* @param array
* @return
*/
static boolean binarySearch(int target, int[] array) {
int front = 0;
int tail = array.length - 1;
// 判断子数组是否能再次二分
while (front <= tail) {
// 获取子数组的中间位置,并依据此中间位置进行二分
int middle = (front + tail) / 2;
if (array[middle] == target) {
return true;
} else if (array[middle] > target) {
tail = middle - 1;
} else {
front = middle + 1;
}
}
return false;
}
public static void main(String[] args) {
int[] array = new int[] { 1, 2, 3, 5, 7, 9, 17, 121, 4545 };
System.out.println(binarySearch(4545, array));
}
}package OrderedArray;
/** * 有序数组
* @author anan
*/
import java.util.Scanner;
class OrderedArray {
private int[] array;
private int nElems;
// 构造函数,生成有序数组对象
public OrderedArray(int max) {
// 生成数组对象
array = new int[max];
// 数组初始元素值为0
nElems = 0;
}
// 返回数组大小
public int size() {
return nElems;
}
// 二分查找
public int BinarySearch(int searchKey) {
int lowBound = 0;
int highBound = nElems - 1;
int currentIndex;
while (true) {
currentIndex = (lowBound + highBound) / 2;
if (array[currentIndex] == searchKey)
// 返回数组中key所在位置
return currentIndex;
if (lowBound > highBound)
return nElems;
else {
if (array[currentIndex] < searchKey) {
lowBound = currentIndex + 1;
} else if (array[currentIndex] > searchKey) {
highBound = currentIndex - 1;
}
}
}
}
// 输入要查找的数
public int input() {
Scanner sc = null;
System.out.println("please input the key you want to search --->");
sc = new Scanner(System.in);
int searchKey = sc.nextInt();
sc.close();
return searchKey;
}
// 显示数组元素
public void display() {
for (int i = 0; i < nElems; i++) {
System.out.print(array[i] + " ");
}
}
// 插入操作
public void insert(int value) {
int i;
for (i = 0; i < nElems; i++) {
if (array[i] > value) {
break;
}
}
for (int j = nElems; j > i; j--) {
// 数组元素依次向后移动一位
array[j] = array[j - 1];
}
array[i] = value;
nElems++;
}
// 删除操作
public boolean delete(int value) {
boolean flag = false;
int j = BinarySearch(value);
if (j == nElems)
flag = false;
else {
for (int k = j; k < nElems; k++) {
array[k] = array[k + 1];
}
nElems--;
flag = true;
}
return flag;
}
};public class OrderedArrayDemo {
public static void main(String[] args) {
int maxSize = 100;
OrderedArray arr = new OrderedArray(maxSize);
arr.insert(11);
arr.insert(32);
arr.insert(5);
arr.insert(26);
arr.insert(45);
arr.insert(88);
arr.insert(1);
arr.insert(9);
arr.delete(9);
arr.delete(88);
System.out.println(arr.size());
System.out.println("---------------------");
arr.display();
System.out.println();
int key = arr.input();
if (arr.BinarySearch(key) != arr.size()) {
System.out.println("found the key!");
} else {
System.out.println("not found the key!");
}
}
}4.二分查找示例二(对链表进行查找)
成员类:二分查找类: