集册 Java实例教程 插值搜索的Java实现

插值搜索的Java实现

欢马劈雪     最近更新时间:2020-01-02 10:19:05

632
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
插值搜索的Java实现



public class Interpolation_Search 

{//N o w J a v a . c o m - 时代Java 提供

    public static int interpolation(int a[], int n, int search_item) // Function implementing Interpolation_Search

    {

        int high = n-1;

        int low = 0;

        int pos;


        while(low <= high && search_item >= a[low] && search_item <= a[high])

        {

            int rise = high - low;

            int run = a[high] - a[low];

            int x = search_item - a[low];

            pos = low + (rise / run) * x;


            if(a[pos] == search_item)
            /** from 
            时 代 J a v a - nowjava.com**/

                return pos;

            else if(search_item < a[pos])

                high = pos - 1;

            else if(search_item > a[pos])

                low = pos + 1;

        }


        return -1;

  }


    // Driver Function

    public static void main(String[] args)

    {

        int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Sorted Input array

        int n = a.length; // Size of array

        int search_item = 8; // Element to be searched

        
展开阅读全文