二分查找问题(Java版)

二分查找问题(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));
    }
}
 
 
 
 

2.Java实现折半查找(二分查找)的递归和非递归算法

 
  1. Java二分查找实现,欢迎大家提出交流意见.  
  2. /** 
  3. *名称:BinarySearch 
  4. *功能:实现了折半查找(二分查找)的递归和非递归算法. 
  5. *说明: 
  6. *     1、要求所查找的数组已有序,并且其中元素已实现Comparable<T>接口,如Integer、String等. 
  7. *    2、非递归查找使用search();,递归查找使用searchRecursively(); 
  8. *本程序仅供编程学习参考 
  9. *@author:   Winty 
  10. *@date:     2008-8-11 
  11. *@email:    wintys@gmail.com 
  12. */  
  13.   
  14. class BinarySearch<T extends Comparable<T>> {  
  15.     private T[]  data;//要排序的数据  
  16.   
  17.     public BinarySearch(T[] data){  
  18.         this.data = data;  
  19.     }  
  20.   
  21.     public int search(T key){  
  22.         int low;  
  23.         int high;  
  24.         int mid;  
  25.   
  26.         if(data == null)  
  27.             return -1;  
  28.   
  29.         low = 0;  
  30.         high = data.length - 1;  
  31.   
  32.         while(low <= high){  
  33.             mid = (low + high) / 2;  
  34.             System.out.println("mid " + mid + " mid value:" + data[mid]);///  
  35.               
  36.             if(key.compareTo(data[mid]) < 0){  
  37.                 high = mid - 1;  
  38.             }else if(key.compareTo(data[mid]) > 0){  
  39.                 low = mid + 1;  
  40.             }else if(key.compareTo(data[mid]) == 0){  
  41.                 return mid;  
  42.             }  
  43.         }  
  44.   
  45.         return -1;  
  46.     }  
  47.   
  48.     private int doSearchRecursively(int low , int high , T key){  
  49.         int mid;  
  50.         int result;  
  51.   
  52.         if(low <= high){  
  53.             mid = (low + high) / 2;  
  54.             result = key.compareTo(data[mid]);  
  55.             System.out.println("mid " + mid + " mid value:" + data[mid]);///  
  56.               
  57.             if(result < 0){  
  58.                 return doSearchRecursively(low , mid - 1 , key);  
  59.             }else if(result > 0){  
  60.                 return doSearchRecursively(mid + 1 , high , key);  
  61.             }else if(result == 0){  
  62.                 return mid;  
  63.             }  
  64.         }  
  65.           
  66.         return -1;  
  67.     }  
  68.   
  69.     public int searchRecursively(T key){  
  70.         if(data ==null)return -1;  
  71.   
  72.         return doSearchRecursively(0 , data.length - 1 , key);  
  73.     }  
  74.   
  75.     public static void main(String[] args){  
  76.         Integer[] data = {1 ,4 ,5 ,8 ,15 ,33 ,48 ,77 ,96};  
  77.         BinarySearch<Integer> binSearch = new BinarySearch<Integer>(data);  
  78.         //System.out.println("Key index:" + binSearch.search(33) );  
  79.   
  80.         System.out.println("Key index:" + binSearch.searchRecursively(3) );  
  81.   
  82.         //String [] dataStr = {"A" ,"C" ,"F" ,"J" ,"L" ,"N" ,"T"};  
  83.         //BinarySearch<String> binSearch = new BinarySearch<String>(dataStr);  
  84.         //System.out.println("Key index:" + binSearch.search("A") );  
  85.     }  
  86. }  
 
 
 
 
 
 
 
 
 
 
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;                 }             }         }     } }
posted on 2017-02-08 20:09  曹明  阅读(326)  评论(0编辑  收藏  举报