请写出该代码:建立一个顺序表,用顺序查找的方法对其实施查找; 再建立一个有序表,用折半查找的方法对其实施查找; 最后建立一个二叉排序树,根据给定值对其实施查找;
时间: 2024-03-16 19:45:50 浏览: 33
好的,我来为您编写这个代码。这里我使用C++语言。
首先,我们需要定义一个顺序表和一个有序表,并实现它们的查找功能:
```c++
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN = 100;
int a[MAXN], b[MAXN];
// 顺序查找
int seq_search(int a[], int n, int x) {
for (int i = 0; i < n; i++) {
if (a[i] == x) return i;
}
return -1;
}
// 折半查找
int bin_search(int a[], int n, int x) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (a[mid] == x) return mid;
else if (a[mid] > x) right = mid - 1;
else left = mid + 1;
}
return -1;
}
```
接下来,我们需要定义一个二叉排序树,并实现其查找功能:
```c++
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 二叉排序树查找
bool bst_search(TreeNode* root, int x) {
if (!root) return false;
if (root->val == x) return true;
else if (root->val > x) return bst_search(root->left, x);
else return bst_search(root->right, x);
}
// 二叉排序树插入
TreeNode* bst_insert(TreeNode* root, int x) {
if (!root) return new TreeNode(x);
if (root->val > x) root->left = bst_insert(root->left, x);
else root->right = bst_insert(root->right, x);
return root;
}
```
最后,我们可以在 main 函数中建立一个顺序表、一个有序表和一个二叉排序树,并对它们进行查找:
```c++
int main() {
// 建立一个顺序表
int n = 10, x = 5;
for (int i = 0; i < n; i++) a[i] = i;
cout << seq_search(a, n, x) << endl;
// 建立一个有序表
for (int i = 0; i < n; i++) b[i] = i;
cout << bin_search(b, n, x) << endl;
// 建立一个二叉排序树
TreeNode* root = NULL;
for (int i = 0; i < n; i++) root = bst_insert(root, i);
cout << bst_search(root, x) << endl;
return 0;
}
```
这样,我们就完成了建立一个顺序表、用顺序查找的方法对其实施查找;再建立一个有序表、用折半查找的方法对其实施查找;最后建立一个二叉排序树,根据给定值对其实施查找的代码。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)