#include<stdio.h>
#include<stdlib.h>

int input(int *a)
{
    int n,i;
    printf("enter the no of elements:");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        printf("enter the element:");
        scanf("%d",a++);
    }
    return n;
}

int key_input(int *a,int key)
{
    int k;
    printf("enter the key value which have to be searched in the array of no's provided:");
    scanf("%d",&k);
    return k;
}

void binary_search(int *a,int n,int key)
{
    int low=0;
    int high=n-1;
    int mid;
    while(low<=high)
    {
        mid=(high+low)/2;

        if(key == a[mid])
        {
            printf("the key:%d is found at location:%d in the array",key,mid);

            if(key==a[mid+1])
            {   
                binary_search(a+mid+1,n-mid-1,key);
            }
            if(key==a[mid-1])
            {
                binary_search(a,n-mid-1,key);
            }
            if(key != a[mid-1] || key != a[mid+1])
            break;
        }

        else if(key < a[mid])
        high=mid-1;

        else if(key>a[mid])
        low=mid+1;
    }
}


int main()
{
    int arr[100];
    int n=input(arr);
    int key=key_input(arr,n);
    binary_search(arr,n,key);
return 0;
}

this is the code which i have written for binary search.I want to find out all the array locations in which the key is present. For Example if i give the key as 4 for the input 4,4,4,4.The output should contain all the locations of the array(0-3).but I don't know wat's wrong with the code,it is running infinetly.some one pls help me.

  1. The array must be in sorted order, you can either enter the numbers that way or call some sort of sort function after input.

  2. Binary search assumes unique values, not duplicate values. The array can contain duplicates but binary search algorithm will find only one of them.

  3. Once one of the values are found the program needs to check other locations immediately before and after the location that was found. Sequential seareches are useful here because binary search can't do that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.