LINEAR AND BINARY SEARCH

[ad_1]

LINEAR AND BINARY SEARCH
#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(
    }
}
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(
        switch (s)
        {
        case 1:
            printf("\n Enter how many elements<=
            scanf(
            inputArray(a, n);
            printf("\n Enter the element to be searched : ");
            scanf(
            pos = searchLinear(a, n, x);
            break;
        case 2:
            printf("\n Enter how many elements<=
            scanf(
            inputArray(a, n);
            printf("\n Enter the element to be searched :");
            scanf(
            pos = searchBinaryNR(a, 0, n, x);
            break;
        case 3:
            printf("\n Enter how many elements<=
            scanf(
            inputArray(a, n);
            printf("\n Enter the element to be searched : ");
            scanf(
            pos = searchBinaryR(a, 0, n, x);
            break;
        default:
            exit(0);
        }
        if (pos != -1)
            printf("\n Element found at
        else
            printf("\n Element not found");
    }
    return 0;
}

[ad_2]

Please follow and like us:
Content Protection by DMCA.com