Data Structures 17 - Sequential Search and Binary Search
Below, we provide a detailed introduction to sequential search and binary search in C, with particular attention to key-value pair scenarios. We will cover basic concepts, data structures, implementation methods, and code examples in a systematic manner.
I. Sequential Search
1. Concept
Sequential search is a simple search algorithm that starts from the first element of a dataset and checks each element one by one until the target element is found or the end of the dataset is reached. The time complexity of sequential search is (O(n)), where (n) is the size of the dataset.
2. Data Structure
We use an array to store key-value pairs. Key-value pairs can be represented using a struct.
#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. Initializing the Sequential Table
When initializing the sequential table, we need to set the initial size to 0.
void initTable(SequentialTable *table) {
table->size = 0;
}
4. Adding Key-Value Pairs
Add key-value pairs to the sequential table.
bool addKeyValuePair(SequentialTable *table, int key, int value) {
if (table->size >= MAX_SIZE) {
return false; // Table is full
}
table->data[table->size].key = key;
table->data[table->size].value = value;
table->size++;
return true;
}
5. Sequential Search Function
Implement the sequential search function that returns the value corresponding to a given key.
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; // Not found
}
6. Complete Example Code
#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 is full
}
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; // Not found
}
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;
}