Advertisement
kdaud

Binary Search Algorithm

Apr 9th, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1. package Interpolation;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class Group {
  6.  
  7.         /** interpolationSearch function **/
  8.         public static int interpolationSearch(int[] sortedArray, int toFind)
  9.         {
  10.             int low = 0;
  11.             int high = sortedArray.length - 1;
  12.             int mid;
  13.             while (sortedArray[low] <= toFind && sortedArray[high] >= toFind)
  14.             {
  15.                 if (sortedArray[high] - sortedArray[low] == 0)
  16.                     return (low + high)/2;
  17.                 /** out of range is possible  here **/
  18.                 mid = low + ((toFind - sortedArray[low]) * (high - low)) / (sortedArray[high] - sortedArray[low]);
  19.  
  20.                 if (sortedArray[mid] < toFind)
  21.                     low = mid + 1;
  22.                 else if (sortedArray[mid] > toFind)
  23.                     high = mid - 1;
  24.                 else
  25.                     return mid;
  26.             }
  27.             if (sortedArray[low] == toFind)
  28.                 return low;
  29.             /** not found **/
  30.             else
  31.                 return -1;
  32.         }
  33.         /** Main method **/
  34.         public static void main(String[] args)
  35.         {
  36.             Scanner scan = new Scanner( System.in );
  37.             System.out.println("Interpolation Search Test\n");
  38.             int n, i;
  39.             /** Accept number of elements **/
  40.             System.out.println("Enter number of integer elements");
  41.             n = scan.nextInt();
  42.             /** Create integer array on n elements **/
  43.             int arr[] = new int[ n ];
  44.             /** Accept elements **/
  45.             System.out.println("\nEnter "+ n +" sorted integer elements");
  46.             for (i = 0; i < n; i++)
  47.                 arr[i] = scan.nextInt();
  48.             System.out.println("\nEnter element to search for : ");
  49.             int key = scan.nextInt();
  50.  
  51.             int result = interpolationSearch(arr, key);
  52.  
  53.             if (result == -1)
  54.                 System.out.println("\n"+ key +" element not found");
  55.             else
  56.                 System.out.println("\n"+ key +" elemnt found at position "+ result);
  57.  
  58.         }
  59.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement