📜  线性和二进制搜索 - C 编程语言代码示例

📅  最后修改于: 2022-03-11 15:04:36.555000             🧑  作者: Mango

代码示例1
#include 
#include 
#define MAX 10
int searchLinear(int a[], int n, int x)
{
    int i;
    for (i = 0; i < n; i++)
    {
        if (a[i] == x)
            return (i + 1);
    }
    return -1;
}

int searchBinaryNR(int a[], int l, int h, int x)
{
    int i, mid;
    while (l <= h)
    {
        mid = (l + h) / 2;
        if (a[mid] == x)
            return (mid + 1);
        else if (x > a[mid])
            l = mid + 1;
        else
            h = mid - 1;
    }
    return -1;
}

int searchBinaryR(int a[], int l, int h, int x)
{
    int i, mid;
    while (l <= h)
    {
        mid = (l + h) / 2;
        if (a[mid] == x)
            return (mid + 1);
        else if (x > a[mid])
            return searchBinaryR(a, mid + 1, h, x);
        else
            return searchBinaryR(a, l, mid + 1, x);
    }
    return -1;
}

void inputArray(int a[], int n)
{
    int i;
    printf("\n Enter array elements:");
    for (i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
    }
}
int main()
{
    int a[MAX], n, s, x, pos;
    while (1)
    {
        printf("\n Press 1 to search using Linear Search Algorithm");
        printf("\n Press 2 to search using Non - Recursive Binary Search Algorithm");
        printf("\n Press 3 to search using Recursive Binary Search Algorithm");
        printf("\n Press 4 to exit");
        printf("\n");
        scanf("%d", &s);
        switch (s)
        {
        case 1:
            printf("\n Enter how many elements<= %d :", MAX);
            scanf("%d", &n);
            inputArray(a, n);
            printf("\n Enter the element to be searched : ");
            scanf("%d", &x);
            pos = searchLinear(a, n, x);
            break;
        case 2:
            printf("\n Enter how many elements<= %d :", MAX);
            scanf("%d", &n);
            inputArray(a, n);
            printf("\n Enter the element to be searched :");
            scanf("%d", &x);
            pos = searchBinaryNR(a, 0, n, x);
            break;
        case 3:
            printf("\n Enter how many elements<= %d :", MAX);
            scanf("%d", &n);
            inputArray(a, n);
            printf("\n Enter the element to be searched : ");
            scanf("%d", &x);
            pos = searchBinaryR(a, 0, n, x);
            break;
        default:
            exit(0);
        }
        if (pos != -1)
            printf("\n Element found at %d position", pos);
        else
            printf("\n Element not found");
    }
    return 0;
}