折半查找的c语言实现

#include <stdio.h>

struct temp {
    int data[10];
    int lenght;
};

int cc(struct temp *t, int tmp[], int n)
{
    int i, ret = 0;
    t->lenght = 0;
    
    for (i = 0; i < n; i++)
    {
        t->data[t->lenght++] = tmp[i];
    }
    putchar('\n');
}

int search(struct temp *t, int min, int max, int n)
{
    int mid;

    if (min < max)
    {
        mid = (min + max) / 2;

        if (n == t->data[mid])
        {
            return 0;
        }
        else if (n < t->data[mid])
        {
            search(t, min, mid-1, n);
        }
        else if (n > t->data[mid])
        {
            search(t, mid+1, max, n);
        }
    }
    
    return -1;
}

int main(void)
{
    int ret = 0;
    struct temp tvn;

    int data[10] = {2, 3, 6, 7, 12, 14, 15, 16, 22, 34};

    cc(&tvn, data, 10);
    
    ret = search(&tvn, 0, 10, 34);
    
    if (ret > 0)
    {
        putchar('o');
        puthcar('k');
    }


你可能感兴趣的:(c,struct,search,语言)