C语言实现数据结构查找算法:折半查找、二叉排序树和哈希表
一、折半查找算法的实现:
#include <stdio.h>
// 折半查找算法
int binarySearch(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // 没有找到目标值
}
int main() {
int arr[] = {1, 3, 5, 7, 9, 11, 13, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 9;
int result = binarySearch(arr, n, target);
if (result != -1) {
printf('目标值在有序表中的索引为:%d\n', result);
} else {
printf('目标值不在有序表中\n');
}
return 0;
}
二、二叉排序树的查找实现:
#include <stdio.h>
#include <stdlib.h>
// 二叉排序树结点定义
typedef struct BSTNode {
int data;
struct BSTNode* left;
struct BSTNode* right;
} BSTNode;
// 创建二叉排序树
BSTNode* createBST(int arr[], int n) {
BSTNode* root = NULL;
for (int i = 0; i < n; i++) {
BSTNode* newNode = (BSTNode*)malloc(sizeof(BSTNode));
newNode->data = arr[i];
newNode->left = NULL;
newNode->right = NULL;
if (root == NULL) {
root = newNode;
} else {
BSTNode* cur = root;
while (1) {
if (arr[i] < cur->data) {
if (cur->left == NULL) {
cur->left = newNode;
break;
} else {
cur = cur->left;
}
} else {
if (cur->right == NULL) {
cur->right = newNode;
break;
} else {
cur = cur->right;
}
}
}
}
}
return root;
}
// 在二叉排序树中查找目标值
BSTNode* searchBST(BSTNode* root, int target) {
BSTNode* cur = root;
while (cur != NULL) {
if (cur->data == target) {
return cur;
} else if (target < cur->data) {
cur = cur->left;
} else {
cur = cur->right;
}
}
return NULL; // 没有找到目标值
}
int main() {
int arr[] = {5, 3, 7, 2, 4, 6, 8};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 4;
BSTNode* root = createBST(arr, n);
BSTNode* result = searchBST(root, target);
if (result != NULL) {
printf('目标值在二叉排序树中\n');
} else {
printf('目标值不在二叉排序树中\n');
}
return 0;
}
三、哈希表查找的实现:
#include <stdio.h>
#include <string.h>
#define SIZE 20 // 哈希表大小
// 哈希表结点定义
typedef struct HashNode {
char name[20];
} HashNode;
// 哈希函数
int hashFunction(char* str) {
int sum = 0;
for (int i = 0; i < strlen(str); i++) {
sum += str[i];
}
return sum % SIZE;
}
// 创建哈希表
void createHashTable(HashNode hashTable[], char* names[], int n) {
for (int i = 0; i < n; i++) {
int index = hashFunction(names[i]);
strcpy(hashTable[index].name, names[i]);
}
}
// 在哈希表中查找目标值
int searchHashTable(HashNode hashTable[], char* target) {
int index = hashFunction(target);
if (strcmp(hashTable[index].name, target) == 0) {
return index;
} else {
return -1; // 没有找到目标值
}
}
int main() {
HashNode hashTable[SIZE];
char* names[] = {'Tom', 'Jerry', 'Alice', 'Bob', 'John'};
int n = sizeof(names) / sizeof(names[0]);
createHashTable(hashTable, names, n);
char* target = 'Alice';
int result = searchHashTable(hashTable, target);
if (result != -1) {
printf('目标值在哈希表中的索引为:%d\n', result);
} else {
printf('目标值不在哈希表中\n');
}
return 0;
}
注意:以上代码只是实现了基本功能,具体数据的输入和调试需要根据实际情况进行修改。
原文地址: https://www.cveoy.top/t/topic/f3YA 著作权归作者所有。请勿转载和采集!