c语言中数组元素的哨兵查找法

c语言中数组元素的哨兵查找法,用于查找数组中是否存在特定的元素,如果存在,就返回目标元素的索引。

像对于线性查找法,哨兵查找法可以减少程序进行判断的次数。

在数组末尾追加的数据称为哨兵。

1、

#include <stdio.h>

#define NUMBER 7
#define FAILED -1

int func1(int x[], int y, int z)
{
    int i = 0;
    x[z] = y;
    
    while (1)
    {
        if (x[i] == y)
            break;
        i++;
    }
    
    return (i < z) ? i : FAILED;
}

int main(void)
{
    int i, a[NUMBER + 1], index, key;
    puts("please input the elements.");
    for (i = 0; i < NUMBER; i++)
    {
        printf("a[%d] : ", i); scanf("%d", &a[i]);
    }
    printf("the target element: "); scanf("%d", &key);
    
    index = func1(a, key, NUMBER);
    if (index == FAILED)
        puts("target element no exist.");
    else
        printf("the order of target element: %d\n", index + 1);
    return 0;
}

 

#include <stdio.h>

#define NUMBER 8
#define FAILED -1

int func1(int x[], int y, int z)
{
    int i;
    x[z] = y;
    
    for (i = 0; x[i] != y; i++)
        ;
    return (i < z) ? i : FAILED;
}

int main(void)
{
    int i, index, key, a[NUMBER + 1];
    puts("please input the elements.");
    for (i = 0; i < NUMBER; i++)
    {
        printf("a[%d] : ", i); scanf("%d", &a[i]);
    }
    printf("input the target element: "); scanf("%d", &key);
    
    index = func1(a, key, NUMBER);
    if (index == FAILED)
        puts("target element no exist.");
    else
        printf("the order of target element: %d\n", index + 1);
    return 0;
}

原文地址:https://www.cnblogs.com/liujiaxin2018/p/14600678.html