当前位置:网站首页>Interpolation lookup and half (bisection) lookup

Interpolation lookup and half (bisection) lookup

2022-06-22 20:01:00 Just one word

The interpolation to find

#include <stdio.h>

int bin_search( int str[], int n, int key )
{
    
    int low, high, mid;
    
    low = 0;
    high = n-1;

    while( low <= high )
    {
    
        mid = low + (key-a[low]/a[high]-a[low])*(high-low); //  The only difference in interpolation lookup 
        
        if( str[mid] == key )
        {
    
            return mid;              
        }
        if( str[mid] < key )
        {
    
            low = mid + 1;       
        }
        if( str[mid] > key )
        {
    
            high = mid - 1;       
        }
    }

    return -1;                      
}

int main()
{
    
    int str[11] = {
    1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
    int n, addr;

    printf(" Please enter the keyword to be found : ");
    scanf("%d", &n);

    addr = bin_search(str, 11, n);
    if( -1 != addr )
    {
    
        printf(" Find success , Gratifying congratulations , Coca Cola !  keyword  %d  The location is : %d\n", n, addr);
    }
    else
    {
    
        printf(" To find the failure !\n");
    }

    return 0;
}

Half ( Two points ) lookup :

#include<stdio.h>
int BinSearch(int arr[],int len,int key)                          // Half search ( Dichotomy )
{
    
	int low=0;                         // Define the initial minimum 
	int high=len-1;                 // Define the initial maximum 
	int mid;                            // Define intermediate values 
	while(low<=high)
	{
    
		mid=(low+high)/2;              // Find the middle value 
		if(key==arr[mid])               // Judge min And key Whether it is equal or not 
			return mid;    
		else if(key>arr[mid])             // If key>mid  Then the new area is [mid+1,high]
			low=mid+1;
		else                                       // If key<mid  Then the new area is [low,mid-1]
			high=mid-1;
	}
	return -1;                             // If there is no target value in the array key, Then return to  -1 ;
}
int main()
{
    
	int arr[]={
    1,2,3,4,5,6,7,8,9,10,11};                      // First of all, we need to set the array arr Sort 
	printf("%d \n",BinSearch(arr,(sizeof(arr)/sizeof(arr[0])),7));
	return 0;
}


原网站

版权声明
本文为[Just one word]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221828272519.html