返回顶部

收藏

线性查找和折半查找的Java实现

更多
package com.gemini.search;

public class Search {

    /**
     * Search the specified array of objects using a linear search<br>
     * algorithm
     * @param data
     * @param target
     * @return boolean found
     */
    public static boolean linearSearch(Comparable[] data, Comparable target) {
        int index = 0;
        boolean found = false;

        while (!found && index <= data.length) {
            if (data[index].compareTo(target) == 0) {
                found = true;
            }
            index++;
        }
        return found;
    }

    /**
     * Search the specified array of objects using a binary search<br>
     * algorithm
     * @param data
     * @param min
     * @param max
     * @param target
     * @return boolean found
     */
    public static boolean binarySearch(Comparable[] data, int min, int max,
            Comparable target) {
        boolean found = false;
        int midpoint = (min + max) / 2; // determine the midpoint

        if (data[midpoint].compareTo(target) == 0) {
            found = true;
        } else if (data[midpoint].compareTo(target) > 0) {
            if (min <= midpoint - 1) {
                found = binarySearch(data, min, midpoint - 1, target);
            }
        } else if (midpoint + 1 <= max) {
            found = binarySearch(data, midpoint + 1, max, target);
        }
        return found;
    }
}
//该片段来自于http://outofmemory.cn

标签:java,算法

收藏

0人收藏

支持

0

反对

0

»更多 您可能感兴趣的代码
  1. 2012-11-05 21:59:42java获得随机数代码 by 怪兽狂殴奥特曼
  2. 2012-11-11 15:02:20通过深度优先搜索产生的迷宫 by 男儿当自强
  3. 2012-11-25 09:28:30java 实现的Boyer-Moore(BM)算法 by 杨洋
  4. 2013-04-23 20:12:31java插入排序 by 山药
  5. 2014-05-28 20:58:04数据结构-栈 by Hugh
  6. 2014-10-12 11:56:24败者树的实现 by Koon.LY
  7. 2013-06-25 16:13:51Blowfish加密算法 by Koon.LY
  8. 2013-10-11 15:33:36Java版球1-n之间的素数 by 云香水识
  9. 2014-05-28 21:17:37选择法冒泡法排序 by 朱凯迪
  10. 2014-06-01 17:41:42Java八皇后 by demon
  11. 2014-07-16 11:53:07Java 列出 2 - 100 之间的所有素数 by 朱凯迪

发表评论