C语言实现数据结构查找算法:折半查找、二叉排序树查找和哈希表查找
一、折半查找算法的实现
#include <stdio.h>
int binarySearch(int arr[], int n, int target) {
int left = 0;
int right = n - 1;
while (left <= right) {
int mid = (left + right) / 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, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 5;
int result = binarySearch(arr, n, target);
if (result == -1) {
printf("Target not found\n");
}
else {
printf("Target found at index %d\n", result);
}
return 0;
}
二、二叉排序树的查找算法的实现
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
}
else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
struct Node* search(struct Node* root, int data) {
if (root == NULL || root->data == data) {
return root;
}
if (data < root->data) {
return search(root->left, data);
}
return search(root->right, data);
}
int main() {
struct Node* root = NULL;
int arr[] = {8, 3, 10, 1, 6, 14, 4, 7, 13};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 6;
for (int i = 0; i < n; i++) {
root = insert(root, arr[i]);
}
struct Node* result = search(root, target);
if (result == NULL) {
printf("Target not found\n");
}
else {
printf("Target found\n");
}
return 0;
}
三、哈希表查找的实现
#include <stdio.h>
#include <string.h>
#define SIZE 10
struct Person {
char name[20];
int age;
};
struct HashTable {
struct Person* table[SIZE];
};
int hash(char* name) {
int sum = 0;
for (int i = 0; i < strlen(name); i++) {
sum += name[i];
}
return sum % SIZE;
}
void insert(struct HashTable* ht, char* name, int age) {
struct Person* newPerson = (struct Person*)malloc(sizeof(struct Person));
strcpy(newPerson->name, name);
newPerson->age = age;
int index = hash(name);
ht->table[index] = newPerson;
}
struct Person* search(struct HashTable* ht, char* name) {
int index = hash(name);
return ht->table[index];
}
int main() {
struct HashTable ht;
memset(&ht, 0, sizeof(ht));
insert(&ht, "Alice", 20);
insert(&ht, "Bob", 25);
insert(&ht, "Charlie", 30);
char target[] = "Bob";
struct Person* result = search(&ht, target);
if (result == NULL) {
printf("Target not found\n");
}
else {
printf("Target found: %s, %d\n", result->name, result->age);
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/f3YE 著作权归作者所有。请勿转载和采集!