数据结构——查找

二分查找

int binSeach(int arr[],int n,int num)
{
    int left = 0;
    int right = n-1;
    int mid = (right + left) / 2;

    while(left <= right)
    {
        if(arr[mid] == num) return mid + 1;
        else if(arr[mid] > num) right = mid - 1;
        else left = mid + 1;

        mid = (right + left) / 2;
    }
    return -1;
}

二叉排序树查找

树节点

typedef struct biTree{
    double key;
    struct biTree *leftchild;
    struct biTree *rightchild;
}biTree;

插入树节点

//函数返回值为根节点,参数为根节点和目标数
biTree* insert(biTree* bit,double num)
{
    biTree* temp = (biTree*)malloc(sizeof(biTree));
    temp->key = num;
    temp->leftchild = temp->rightchild = NULL;

    if(bit == NULL)
    {
        bit = temp;
        return bit;
    }
    else
    {
        biTree* p = bit;
        while(num != p->key)
        {
            if((num < p->key) && p->leftchild)
                p = p->leftchild;
            else if((num > p->key) && p->rightchild)
                p = p->rightchild;
            else if((num < p->key) && !p->leftchild)
            {
                p->leftchild = temp;
                return bit;
            }
            else if((num > p->key) && !p->rightchild)
            {
                p->rightchild = temp;
                return bit;
            }
        }
    }
    return bit;
}

上一篇:JM-S03061AH-002 verilog 驱动程序


下一篇:通过DSP采集AD7606的转换结果