Formula for Interpolation Search is => mid = l + ((h - l) / (arr[h] - arr[l])) * (key - arr[l]);
code is => #include<stdio.h> #include<stdlib.h> #include<math.h> #define max 10 int main() { int arr[max],i,l,h,mid,key; printf("Enter the elements into the array\n"); for(i=0;i<max;i++) { scanf("%d",&arr[i]); } printf("Enter the key value which you wan't to search\n"); scanf("%d",&key); l=0; h=max-1; while(h>=l) { mid = l + ((h - l) / (arr[h] - arr[l])) * (key - arr[l]); if(arr[mid]==key) { printf("element found at index arr[%d]\n",mid); return 0; } else if(key<arr[mid]) { h = mid - 1; } else { l = mid + 1; } } printf("Key value is not present into the array\n"); return -1; }
not working for only the series given below when find key value 12 or 13 1,3,5,7,9,11,15,16,17,18
================================================================== Try it with any series ==================================================================
I tried with make some changes in the formula and i got a solution for Interpolation search,Now my code works for all the series of sorted elements. Edited Formulas => mid = l + ((h - l+1) / (*(ptr+h) - (*(ptr+l)+1))) * (key - *(ptr+l)); and, previous formula is => mid = l + ((h - l) / (*(ptr+h) - (*(ptr+l))) * (key - *(ptr+l));
When both high(h) and low(l) become equal then compiler show Floating point exception. so to overcome from this situation i incremented value of l by 1....