c语言如何实现数据的查找

   2025-02-15 8490
核心提示:在C语言中,可以使用线性搜索、二分搜索、哈希表等方式实现数据的查找。线性搜索:线性搜索是最简单的查找方法,它通过遍历数据

在C语言中,可以使用线性搜索、二分搜索、哈希表等方式实现数据的查找。

线性搜索:线性搜索是最简单的查找方法,它通过遍历数据集合中的每一个元素,逐个与目标值进行比较,直到找到目标值或遍历完整个数据集合。
#include <stdio.h>int linearSearch(int arr[], int n, int target) {    for (int i = 0; i < n; i++) {        if (arr[i] == target) {            return i;  // 返回目标值在数组中的索引        }    }    return -1;  // 表示未找到目标值}int main() {    int arr[] = {1, 2, 3, 4, 5};    int n = sizeof(arr) / sizeof(arr[0]);    int target = 3;    int result = linearSearch(arr, n, target);    if (result == -1) {        printf("未找到目标值\n");    } else {        printf("目标值在数组中的索引为:%d\n", result);    }    return 0;}
二分搜索:二分搜索要求数据集合必须是有序的,它通过将数据集合分成两部分,然后与目标值进行比较,确定目标值可能在哪部分,再在相应的部分进行继续二分搜索,直到找到目标值或确定目标值不存在。
#include <stdio.h>int binarySearch(int arr[], int low, int high, int target) {    while (low <= high) {        int mid = low + (high - low) / 2;        if (arr[mid] == target) {            return mid;  // 返回目标值在数组中的索引        }        if (arr[mid] < target) {            low = mid + 1;        } else {            high = mid - 1;        }    }    return -1;  // 表示未找到目标值}int main() {    int arr[] = {1, 2, 3, 4, 5};    int n = sizeof(arr) / sizeof(arr[0]);    int target = 3;    int result = binarySearch(arr, 0, n - 1, target);    if (result == -1) {        printf("未找到目标值\n");    } else {        printf("目标值在数组中的索引为:%d\n", result);    }    return 0;}
哈希表:哈希表是一种以键值对存储数据的数据结构,它通过将键映射到一个固定大小的数组中,实现高效的数据查找。
#include <stdio.h>#include <stdbool.h>#define SIZE 10typedef struct {    int key;    int value;} Entry;Entry hashTable[SIZE];int hashCode(int key) {    return key % SIZE;}void insert(int key, int value) {    int index = hashCode(key);    while (hashTable[index].key != 0) {        index = (index + 1) % SIZE;    }    hashTable[index].key = key;    hashTable[index].value = value;}bool search(int key, int* value) {    int index = hashCode(key);    int count = 0;    while (hashTable[index].key != 0) {        if (count > SIZE) {            return false;  // 哈希表已满,未找到目标值        }        if (hashTable[index].key == key) {            *value = hashTable[index].value;            return true;  // 找到目标值        }        index = (index + 1) % SIZE;        count++;    }    return false;  // 未找到目标值}int main() {    insert(1, 10);    insert(2, 20);    insert(3, 30);    int target = 2;    int value;    if (search(target, &value)) {        printf("目标值的键:%d,值:%d\n", target, value);    } else {        printf("未找到目标值\n");    }    return 0;}

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言