查找算法总结之顺序查找、二分查找、静态树查找

#include <iostream> using namespace std; //顺序查找, 平均查找长度为(n + 1)/2 int search_sq(int array[], int array_len, int key) { for (int i = 0; i < array_len; ++i) { if (key == array[i]) { return i; } } return -1; } //二分查找,平均查找查找长度为〖log2 (N+1〗 – 1,但是序列必须是有序的 int search_binary(int array[], int array_len, int key) { int left = 0; int right = array_len -1; while (left <= right) { int middle = (left + right)/2; if (array[middle] == key) { return middle; } else if (array[middle] > key) { right = middle – 1; } else left = middle + 1; } return -1; } //二叉树查找 struct BSTreeNode { int data; BSTreeNode* left_child;//左孩子 BSTreeNode* right_child; //右孩子 }; typedef BSTreeNode* BSTree; BSTreeNode* pNode = NULL; // 根据结点值创建数目 void Create(BSTree& tree, int data) { if (tree == NULL) { tree = new BSTreeNode; tree->left_child = NULL; tree->right_child = NULL; tree->data = data; } else { if (tree->data > data) { Create(tree->left_child, data); } else if (tree->data < data) { Create(tree->right_child, data); } else return; } } //创建二叉树 void CreateBSTree(int array[], int array_len) { for (int i = 0; i < array_len; ++i) { Create(pNode, array[i]); } } //查找树查找,平均查找查找长度为〖log2 (N+1〗 – 1 BSTreeNode* search_binaryTree(BSTree tree, int data) { if (tree == NULL) { return NULL; } if (tree->data == data) { return tree; } else if (tree->data > data) { return search_binaryTree(tree->left_child, data); } else return search_binaryTree(tree->right_child, data); } int main() { int a[10] ={2, 5, 1, 8, 9}; cout<<“顺序查找元素8的位置是:”<<search_sq(a, 5, 8)<<endl; int b[7] = {1, 2, 3, 3, 5, 6}; cout<<“二分查找元素3的位置是:”<<search_binary(b, 7, 3)<<endl; CreateBSTree(a, 5); cout<<“二叉树查找是否存在8:”; CreateBSTree(a, 5); BSTreeNode* find = search_binaryTree(pNode, 8); cout<<find->data<<endl; find = search_binaryTree(pNode, 10); if (find == NULL) { cout<<“不存在10!”; } return 0; }

    原文作者:查找算法
    原文地址: https://blog.csdn.net/acdnjjjdjkdckjj/article/details/6248847
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞