C语言静态查找表的查找算法(顺序查找、折半查找)

 

 

顺序查找的实现

#include <stdio.h>

#define SIZE 10  // 静态查找表的大小

// 顺序查找函数
int sequentialSearch(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return i;  // 查找成功,返回目标的索引
        }
    }
    return -1;  // 查找失败
}

int main() {
    int staticTable[SIZE] = {23, 45, 12, 67, 34, 89, 10, 77, 55, 31};  // 静态查找表
    int target;

    printf("请输入要查找的数字:");
    scanf("%d", &target);

    int index = sequentialSearch(staticTable, SIZE, target);
    if (index != -1) {
        printf("找到数字 %d ,它在索引 %d 上。\n", target, index);
    } else {
        printf("数字 %d 不在查找表中。\n", target);
    }

    return 0;
}

 

 

折半查找的实现

#include <stdio.h>

#define SIZE 10  // 静态查找表的大小

// 折半查找函数(二分查找)
int binarySearch(int arr[], int size, int target) {
    int low = 0;
    int high = size - 1;

    while (low <= high) {
        int mid = (low + high) / 2;  // 计算中间索引
        if (arr[mid] == target) {
            return mid;  // 查找成功,返回索引
        } else if (arr[mid] < target) {
            low = mid + 1;  // 在右半部分继续查找
        } else {
            high = mid - 1;  // 在左半部分继续查找
        }
    }
    return -1;  // 查找失败
}

int main() {
    int staticTable[SIZE] = {10, 12, 23, 31, 34, 45, 55, 67, 77, 89};  // 静态查找表(有序)
    int target;

    printf("请输入要查找的数字:");
    scanf("%d", &target);

    int index = binarySearch(staticTable, SIZE, target);
    if (index != -1) {
        printf("找到数字 %d ,它在索引 %d 上。\n", target, index);
    } else {
        printf("数字 %d 不在查找表中。\n", target);
    }

    return 0;
}

 

posted @ 2025-02-15 10:01  漫漫长路</>  阅读(101)  评论(0)    收藏  举报