查找

一、顺序查找

1.无哨兵

int SequentailSearch(StaticTable* Tbl, ElemenType k)
{
    int i;
    for (i = Tbl->Length; i > 0 && Element[i] != k; i--);
    return i;
}

2.有哨兵

int SequentailSearch(StaticTable* Tbl, ElemenType k)
{
    int i;
    Tbl->Element[0] = k;//建立哨兵
    for (i = Tbl->Length(); lement[i] != k; i--);
    return i;
}

二、二分查找

注意:必须是数组存储、元素有序

int BinarySearch(List Tbl, ElemType K)
{//List 两个分量,一个是数组Element,一个是它的大小Length
    int left, right, mid, NoFound == -1;
    left = 1; right = Tbl->Length;
    while (left <= right)
    {
        mid = (left + right) / 2;
        if (K == Tbl->Element[mid])
            return mid;
        else if (Tbl->Element[mid] > k)
        {
            right = mid;
        }
        else
            left = mid;
    }
    return NoFound ;
}

 

上一篇:HDU - 2063


下一篇:mongoDB日常操作03