数据结构17-顺序查找与二分查找
好的,下面我们将详细介绍C语言中的顺序查找和二分查找,特别是针对键值对的情况。我们会从基本概念、数据结构、实现方法和代码示例等方面进行系统讲解。
一、顺序查找(Sequential Search)
1. 概念
顺序查找是一种简单的查找算法,它从数据集的第一个元素开始,逐个检查每个元素,直到找到目标元素或到达数据集的末尾。顺序查找的时间复杂度为 (O(n)),其中 (n) 是数据集的大小。
2. 数据结构
我们使用一个数组来存储键值对。键值对可以使用结构体来表示。
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 100
typedef struct {
int key;
int value;
} KeyValuePair;
typedef struct {
KeyValuePair data[MAX_SIZE];
int size;
} SequentialTable;
3. 初始化顺序表
初始化顺序表时,我们需要设置初始大小为0。
void initTable(SequentialTable *table) {
table->size = 0;
}
4. 添加键值对
向顺序表中添加键值对。
bool addKeyValuePair(SequentialTable *table, int key, int value) {
if (table->size >= MAX_SIZE) {
return false; // 表已满
}
table->data[table->size].key = key;
table->data[table->size].value = value;
table->size++;
return true;
}
5. 顺序查找函数
实现顺序查找函数,返回键对应的值。
int sequentialSearch(SequentialTable *table, int key) {
for (int i = 0; i < table->size; i++) {
if (table->data[i].key == key) {
return table->data[i].value;
}
}
return -1; // 未找到
}
6. 完整示例代码
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 100
typedef struct {
int key;
int value;
} KeyValuePair;
typedef struct {
KeyValuePair data[MAX_SIZE];
int size;
} SequentialTable;
void initTable(SequentialTable *table) {
table->size = 0;
}
bool addKeyValuePair(SequentialTable *table, int key, int value) {
if (table->size >= MAX_SIZE) {
return false; // 表已满
}
table->data[table->size].key = key;
table->data[table->size].value = value;
table->size++;
return true;
}
int sequentialSearch(SequentialTable *table, int key) {
for (int i = 0; i < table->size; i++) {
if (table->data[i].key == key) {
return table->data[i].value;
}
}
return -1; // 未找到
}
int main() {
SequentialTable table;
initTable(&table);
addKeyValuePair(&table, 1, 100);
addKeyValuePair(&table, 2, 200);
addKeyValuePair(&table, 3, 300);
int key = 2;
int value = sequentialSearch(&table, key);
if (value != -1) {
printf("Key %d found with value %d\n", key, value);
} else {
printf("Key %d not found\n", key);
}
return 0;
}