返回顶部

收藏

线性查找和折半查找的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

发表评论