Advertisement
Shailrshah

Interpolation Search

Nov 5th, 2013
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.93 KB | None | 0 0
  1. #include <stdio.h>
  2. void sort(int a[],int n){
  3.     int i, j;
  4.     for(i = 1; i < n; i++){
  5.         int temp = a[i];
  6.         for(j = i-1; j >= 0 && temp < a[j]; j--) a[j+1] = a[j];
  7.         a[j+1] = temp;
  8.     }
  9. }
  10. int search(int a[], int low, int high, int x){
  11.     int mid;
  12.     while(a[low]<=x && a[high]>=x){
  13.         mid = low + ( (x - a[low]) * (high - low) ) / (a[high] - a[low]);
  14.         if(a[mid] < x) low = mid + 1;
  15.         else if(a[mid] > x) high = mid + 1;
  16.         else return mid;
  17.     }
  18.     if(a[low] == x) return x;
  19.     else return -1;
  20. }
  21. int main(){
  22.     int a[20];
  23.     int length,x;
  24.     printf("Enter the number of numbers: ");
  25.     scanf("%d", &length);
  26.     printf("Enter the numbers:-\n");
  27.     for(int i = 0; i<length; i++) scanf("%d", &a[i]);
  28.     sort(a,length);
  29.     for(int i = 0; i<length; i++) printf("%d\t", a[i]);
  30.     printf("\nEnter the element to search: ");
  31.     scanf("%d", &x);
  32.     int result = search(a, 0, length-1, x);
  33.     if(result != -1) printf("%d found at %d", x, result);
  34.     else printf("Not Found!");
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement