NAV BAR

Monday, 8 August 2016

Jump Search in C

#include<stdio.h>
#include<conio.h>
#define MAX 20
int jumpSearch(int a[],int n,int val);
int main()
{
    int pos,i,val,a[MAX],n;
    printf("Enter number of value \n");
    scanf("%d",&n);
    printf("Enter value of each element\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("Enter value to be searched\n");
    scanf("%d",&val);
    pos = jumpsearch(a,n,val);
    if(pos ==-1)
    {
        printf("Element not found\n");
    }
    else
    {
        printf("Element found at position %d",(pos+1));
    }
    getch();
    return 0;
}
int jumpsearch(int a[],int n,int val)
{
    int mid,low =0,high = n-1;
    int step,i;
    step = sqrt(n);
    for(i=0;i<step;i++)
    {
        if(val<a[step])
        {
            high = step - 1;
        }
        else
        {
            low = step + 1;
        }
    }
    for(i=low;i<=high;i++)
    {
        if(a[i]==val)
        {
            return i;
        }
    }
    return -1;
}

No comments:

Post a Comment