mirror of
https://github.moeyy.xyz/https://github.com/TheAlgorithms/C.git
synced 2023-10-11 15:56:24 +08:00
Merge pull request #120 from akshayanvi/patch-1
Update interpolation_search.c
This commit is contained in:
commit
f46a602704
@ -1,24 +1,12 @@
|
||||
|
||||
#include<stdio.h>
|
||||
int interpolationSearch(int arr[], int n, int x)
|
||||
{
|
||||
int lo = 0, hi = (n - 1);
|
||||
|
||||
while (lo <= hi && x >= arr[lo] && x <= arr[hi])
|
||||
{
|
||||
int q=NULL;
|
||||
while(q<n)
|
||||
{
|
||||
|
||||
int pos = lo + (((double)(hi-lo) /
|
||||
(arr[hi]-arr[lo]))*(x - arr[lo]));
|
||||
|
||||
|
||||
if (arr[pos] == x)
|
||||
return pos;
|
||||
|
||||
|
||||
if (arr[pos] < x)
|
||||
lo = pos + 1;
|
||||
|
||||
else
|
||||
hi = pos - 1;
|
||||
if(arr[q]==x)
|
||||
return q;
|
||||
q++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
@ -28,16 +16,19 @@ int main()
|
||||
{
|
||||
// Array of items on which search will
|
||||
// be conducted.
|
||||
int x;
|
||||
int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, 22, 23,
|
||||
24, 33, 35, 42, 47};
|
||||
int n = sizeof(arr)/sizeof(arr[0]); //To get length of an array
|
||||
|
||||
int x = 18; // Element to be searched
|
||||
|
||||
printf("Enter the no, to be searched");
|
||||
scanf("%d",&x); // Element to be searched
|
||||
|
||||
int index = interpolationSearch(arr, n, x);
|
||||
|
||||
// If element was found
|
||||
if (index != -1)
|
||||
printf("Element found at index %d", index);
|
||||
printf("Element found at position %d", index+1);
|
||||
else
|
||||
printf("Element not found.");
|
||||
return 0;
|
||||
|
Loading…
Reference in New Issue
Block a user