二分查找问题(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)); }}- Java二分查找实现,欢迎大家提出交流意见.
- /**
- *名称:BinarySearch
- *功能:实现了折半查找(二分查找)的递归和非递归算法.
- *说明:
- * 1、要求所查找的数组已有序,并且其中元素已实现Comparable<T>接口,如Integer、String等.
- * 2、非递归查找使用search();,递归查找使用searchRecursively();
- *
- *本程序仅供编程学习参考
- *
- *@author: Winty
- *@date: 2008-8-11
- *@email: wintys@gmail.com
- */
- class BinarySearch<T extends Comparable<T>> {
- private T[] data;//要排序的数据
- public BinarySearch(T[] data){
- this.data = data;
- }
- public int search(T key){
- int low;
- int high;
- int mid;
- if(data == null)
- return -1;
- low = 0;
- high = data.length - 1;
- while(low <= high){
- mid = (low + high) / 2;
- System.out.println("mid " + mid + " mid value:" + data[mid]);///
- if(key.compareTo(data[mid]) < 0){
- high = mid - 1;
- }else if(key.compareTo(data[mid]) > 0){
- low = mid + 1;
- }else if(key.compareTo(data[mid]) == 0){
- return mid;
- }
- }
- return -1;
- }
- private int doSearchRecursively(int low , int high , T key){
- int mid;
- int result;
- if(low <= high){
- mid = (low + high) / 2;
- result = key.compareTo(data[mid]);
- System.out.println("mid " + mid + " mid value:" + data[mid]);///
- if(result < 0){
- return doSearchRecursively(low , mid - 1 , key);
- }else if(result > 0){
- return doSearchRecursively(mid + 1 , high , key);
- }else if(result == 0){
- return mid;
- }
- }
- return -1;
- }
- public int searchRecursively(T key){
- if(data ==null)return -1;
- return doSearchRecursively(0 , data.length - 1 , key);
- }
- public static void main(String[] args){
- Integer[] data = {1 ,4 ,5 ,8 ,15 ,33 ,48 ,77 ,96};
- BinarySearch<Integer> binSearch = new BinarySearch<Integer>(data);
- //System.out.println("Key index:" + binSearch.search(33) );
- System.out.println("Key index:" + binSearch.searchRecursively(3) );
- //String [] dataStr = {"A" ,"C" ,"F" ,"J" ,"L" ,"N" ,"T"};
- //BinarySearch<String> binSearch = new BinarySearch<String>(dataStr);
- //System.out.println("Key index:" + binSearch.search("A") );
- }
- }
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.二分查找示例二(对链表进行查找)
成员类:
package com.junglesong;
public class Member implements Comparable{
private String name;
private int age;
public Member(String name,int age){
this.name=name;
this.age=age;
}
/**
* 实现成员比较
*/
public int compareTo(Object obj){
Member another=(Member)obj;
return this.name.compareTo(another.name);
}
/**
* 实现成员相等运算
*/
public boolean equals(Object obj){
Member another=(Member)obj;
return this.name.equals(another.name);
}
public String toString(){
return "名="+name+" 年龄="+age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}二分查找类:
package com.junglesong;
import java.util.ArrayList;
import java.util.List;
/**
* 二分查找示例二(对链表进行查找)
* @author: sitinspring(junglesong@gmail.com)
* @date: 2008-3-8
*/
public class BinSearch2{
public static void main(String[] args){
// 欲查找的链表
List<Member> members=new ArrayList<Member>();
members.add(new Member("Andy",21));
members.add(new Member("Bill",22));
members.add(new Member("Cindy",23));
members.add(new Member("Douglas",24));
members.add(new Member("Felex",25));
members.add(new Member("Green",26));
// 测试链表
List<Member> tempList=new ArrayList<Member>();
tempList.add(new Member("Bill",22));
tempList.add(new Member("Cindy",23));
tempList.add(new Member("Douglas",24));
tempList.add(new Member("Felex",25));
tempList.add(new Member("Hill",26));
for(Member member:tempList){
System.out.println("成员"+member+"的下标为"+binSearch(members,member));
}
}
/**
* 二分查找
* @param sortedArray 已排序的欲查找的链表
* @param seachValue 查找的值
* @return 找到的元素下标,若找不到则返回-1
*/
public static int binSearch(List<Member> sortedList,Member seachValue){
// 左边界
int leftBound=0;
// 右边界
int rightBound=sortedList.size()-1;
// 当前下标位置
int curr;
while(true){
// 定位在左边界和右边界中间
curr=(leftBound+rightBound)/2;
if(sortedList.get(curr).equals(seachValue)){
// 找到值
return curr;
}
else if(leftBound>rightBound){
// 左边界大于右边界,已经找不到值
return -1;
}
else{
if(sortedList.get(curr).compareTo(seachValue)<0){
// 当当前下标对应的值小于查找的值时,缩短左边界
leftBound=curr+1;
}
else{
// 当当前下标对应的值大于查找的值时,缩短右边界
rightBound=curr-1;
}
}
}
}
}