Dichotomy search:

The lookup function is an essential function of data processing. Data lookup is not complicated, but how to realize data lookup quickly and well? Some methods accumulated by predecessors in practice are worth learning. We assume that the searched data is unique and no duplicate data exists in the array.

Sequential search, binary search, binary tree search, hash search.

Dichotomy search:

a is the array to be searched, and the precondition for binary search is that the sorting of the data of a is ordered. key is the variable to be searched, and n is the length of the array a.

int binary( int *a, int key, int n )
{
    int left = 0, right = n - 1, mid = 0;
    mid = ( left + right ) / 2;
    while( left < right && a[mid] != key )
    {
        if( a[mid] < key )
        left = mid + 1;
        else if( a[mid] > key )
        right = mid - 1;
        mid = ( left + right ) / 2;
    }
    if( a[mid] == key )   return mid;
    return -1;
}

 

transfer:

Find the position of the subscript of array b in array a (when the data in b does not exist in a, use -1 instead).

int main()
{
    int a[] = {1,2,3,4,5,6,7,8,9,12,13,45,67,89,99,101,111,123,134,565,677};
    int b[] = { 677, 1, 7, 11, 67 };
    int i;
    for( i=0; i
    {
        printf( "%d\n", binary( a, b[i], sizeof(a)/sizeof(a[0])));
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326268265&siteId=291194637