查找

查找

顺序查找

#define ElemType int
#define MaxSize 10
typedef struct {
   ElemType* elem; //动态数组基地址
   int TableLen;   //表长
} SSTable;
int Search_Seq1(SSTable L, ElemType key) {
   L.elem[0] = key;
   int i;
   for (i = L.TableLen; L.elem[i] != key; --i)
       ;     //从后往前找
   return i; //若表中不存在关键字为key的元素,将查找到i为0时退出for循环
}

int Search_Seq2(SSTable L, ElemType key) {
   int i;
   for (int i = 0; i < L.TableLen && L.elem[i] != key; i++)
       ;
   return i == L.TableLen ? -1 : i;
}

折半查找

#define ElemType int
#define MaxSize 10
typedef struct {
    ElemType* elem; //动态数组基地址
    int TableLen;   //表长
} SSTable;
//折半查找
int Binary_Search(SSTable L, ElemType key) {
    int low = 0, high = L.TableLen - 1, mid;
    while (low <= high) {
        mid = (high + low) / 2;
        if (L.elem[mid] == key) {
            return mid;
        } else if (L.elem[mid] > key) {
            high = mid - 1;

        } else {
            low = mid + 1;
        }
    }
    return -1;
}

二叉排序树

typedef struct BSTNode {
    int key;
    int length;
    struct BSTNode *lchild, *rchild;
} BSTNode, *BSTree;

//在二叉排序树中查找-非递归实现
BSTNode* BST_Search(BSTree T, int key) {
    while (T != NULL && key != T->key) {
        if (key < T->key)
            T = T->lchild;
        else
            T = T->rchild;
    }
    return T;
}
//在二叉排序树中查找-递归实现
BSTNode* BST_Search2(BSTree T, int key) {
    if (T == NULL) {
        return NULL;
    }
    if (key == T->key) {
        return T;
    } else if (key > T->key) {
        return BST_Search(T->rchild, key);
    } else {
        return BST_Search(T->lchild, key);
    }
}

//二叉排序树的插入
bool Bst_Insert(BSTree& T, int key) {

    if (T == NULL) {
        T = (BSTNode*)malloc(sizeof(BSTNode));
        T->key = key;
        T->lchild = NULL;
        T->rchild = NULL;

        return true;
    } else if (key == T->key) {
        return false;
    } else if (key > T->key) {
        return Bst_Insert(T->rchild, key);
    } else {
        return Bst_Insert(T->lchild, key);
    }
    return true;
}
//二叉排序树的构造
//按照str[]中的关键字序列建立二叉排序树
void Create_BST(BSTree& T, int str[], int n) {
    T = NULL; //初始时T为空树
    int i = 0;
    while (i < n) {
        Bst_Insert(T, str[i]);
        i++;
    }
}
int main() {
    BSTree T;
    int str[4];
    Create_BST(T, str, 4);
}

T O(1)
posted @ 2023-09-24 20:57  Zh'Blog  阅读(35)  评论(0编辑  收藏  举报