Bitcoin

Bitcoin
Bitcoin

Interpolation Search

Interpolation search is an algorithm for searching for a given key in an indexed array that has been ordered by numerical values assigned to the keys (key values). It parallels how humans search through a telephone book for a particular name, the key value by which the book's entries are ordered.
Given a sorted array of n uniformly distributed values arr[], write a function to search for a particular element x in the array.
Linear Search finds the element in O(n) time, Jump Search takes O(√ n) time and Binary Search take O(Log n) time.
The Interpolation Search is an improvement over Binary Search for instances, where the values in a sorted array are uniformly distributed. Binary Search always goes to middle element to check. On the other hand interpolation search may go to different locations according the value of key being searched. For example if the value of key is closer to the last element, interpolation search is likely to start search toward the end side.
To find the position to be searched, it uses following formula.
// The idea of formula is to return higher value of pos
// when element to be searched is closer to arr[hi]. And
// smaller value when closer to arr[lo]
pos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[Lo]) ]

arr[] ==> Array where elements need to be searched
x     ==> Element to be searched
lo    ==> Starting index in arr[]
hi    ==> Ending index in arr[]
Algorithm
Rest of the Interpolation algorithm is same except the above partition logic.
Step1: In a loop, calculate the value of “pos” using the probe position formula.
Step2: If it is a match, return the index of the item, and exit.
Step3: If the item is less than arr[pos], calculate the probe position of the left sub-array. Otherwise calculate the same in the right sub-array.
Step4: Repeat until a match is found or the sub-array reduces to zero.
// Java program to implement interpolation search
class Test
{
    // Array of items on which search will
    // be conducted.
    static int arr[] = new int[]{10, 12, 13, 16, 18, 19, 20, 21, 22, 23,
                                         24, 33, 35, 42, 47};
    // If x is present in arr[0..n-1], then returns
    // index of it, else returns -1.
    static int interpolationSearch(int x)
    {
        // Find indexes of two corners
        int lo = 0, hi = (arr.length - 1);
      
        // Since array is sorted, an element present
        // in array must be in range defined by corner
        while (lo <= hi && x >= arr[lo] && x <= arr[hi])
        {
            // Probing the position with keeping
            // uniform distribution in mind.
            int pos = lo + (((hi-lo) /
                  (arr[hi]-arr[lo]))*(x - arr[lo]));
      
            // Condition of target found
            if (arr[pos] == x)
                return pos;
            // If x is larger, x is in upper part
            if (arr[pos] < x)
                lo = pos + 1;
      
            // If x is smaller, x is in lower part
            else
                hi = pos - 1;
        }
        return -1;
    }
   
    // Driver method 
    public static void main(String[] args) 
    {
         int x = 18; // Element to be searched
         int index = interpolationSearch(x);
          
         // If element was found
         if (index != -1)
            System.out.println("Element found at index " + index);
         else
            System.out.println("Element not found.");
    }
}

Output :
Element found at index 4

Time Complexity : If elements are uniformly distributed, then O (log log n)).
In worst case it can take up to O(n).
Auxiliary Space : O(1)


/**
 ** Java Program to Implement Interpolation Search Algorithm
 **/
 
import java.util.Scanner;
 
/** Class InterpolationSearch **/
public class InterpolationSearch
{
    /** interpolationSearch function **/
    public static int interpolationSearch(int[] sortedArray, int toFind)
    {
        int low = 0;
        int high = sortedArray.length - 1;
        int mid;
        while (sortedArray[low] <= toFind && sortedArray[high] >= toFind) 
        {
            if (sortedArray[high] - sortedArray[low] == 0)
                return (low + high)/2;
            /** out of range is possible  here **/
             mid = low + ((toFind - sortedArray[low]) * (high - low)) / 
                        (sortedArray[high] - sortedArray[low]);  
 
             if (sortedArray[mid] < toFind)
                 low = mid + 1;
             else if (sortedArray[mid] > toFind)
                 high = mid - 1;
             else
                 return mid;
        }
        if (sortedArray[low] == toFind)
            return low;
           /** not found **/
        else
            return -1; 
    }    
    /** Main method **/
    public static void main(String[] args) 
    {
        Scanner scan = new Scanner( System.in );        
        System.out.println("Interpolation Search Test\n");
        int n, i;
        /** Accept number of elements **/
        System.out.println("Enter number of integer elements");
        n = scan.nextInt();
        /** Create integer array on n elements **/
        int arr[] = new int[ n ];
        /** Accept elements **/
        System.out.println("\nEnter "+ n +" sorted integer elements");
        for (i = 0; i < n; i++)
            arr[i] = scan.nextInt();
        System.out.println("\nEnter element to search for : ");
        int key = scan.nextInt();
        int result = interpolationSearch(arr, key);
        if (result == -1)
            System.out.println("\n"+ key +" element not found");
        else
            System.out.println("\n"+ key +" elemnt found at position "+ result);
    }    
}
Interpolation Search Test
 
Enter number of integer elements
10
 
Enter 10 sorted integer elements
12 24 36 48 60 72 84 96 108 120
 
Enter element to search for :
24
 
24 elemnt found at position 1


No comments:

Post a Comment

Facebook