利用顺序查找,二分查找,二叉排序树查找实现对整数的查找,c语言
时间: 2023-07-18 19:34:47 浏览: 108
好的,我可以为您提供一些代码示例:
顺序查找:
```c
int sequentialSearch(int arr[], int n, int x) {
for(int i=0; i<n; i++) {
if(arr[i] == x) {
return i;
}
}
return -1; //未找到
}
```
二分查找:
```c
int binarySearch(int arr[], int l, int r, int x) {
if(r >= l) {
int mid = l + (r-l)/2;
if(arr[mid] == x) {
return mid;
}
if(arr[mid] > x) {
return binarySearch(arr, l, mid-1, x);
}
return binarySearch(arr, mid+1, r, x);
}
return -1; //未找到
}
```
二叉排序树查找:
```c
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* insert(TreeNode* root, int val) {
if(root == NULL) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
if(val < root->val) {
root->left = insert(root->left, val);
} else if(val > root->val) {
root->right = insert(root->right, val);
}
return root;
}
TreeNode* search(TreeNode* root, int val) {
if(root == NULL || root->val == val) {
return root;
}
if(val < root->val) {
return search(root->left, val);
}
return search(root->right, val);
}
void inorderTraversal(TreeNode* root) {
if(root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
}
int main() {
int arr[] = {2, 5, 1, 8, 3, 9, 4, 6, 7};
int n = sizeof(arr)/sizeof(arr[0]);
TreeNode* root = NULL;
for(int i=0; i<n; i++) {
root = insert(root, arr[i]);
}
inorderTraversal(root); //1 2 3 4 5 6 7 8 9
TreeNode* node = search(root, 5);
if(node != NULL) {
printf("\n%d found in the tree!", node->val); //5 found in the tree!
} else {
printf("\n5 not found in the tree!");
}
return 0;
}
```
希望可以帮到您!
阅读全文