Sunday 10 January 2016

Binary Search in a Sorted Array (Algorithm 4.6)


Before seeing the solution make sure that you tried enough. Don’t paste the whole code, just find out the logic. If you stuck in trouble, just inform me on comment.

/**Bismillahir Rahmanir Rahim.**/

#include <stdio.h>
int main()
{
    int N, i,LB,UB, ITEM, BIG, MID, END;
    scanf("%d", &N);
    int DATA[N];
    for(i=0; i<N; i++) scanf("%d", &DATA[i]);
    scanf("%d", &ITEM);
    scanf("%d%d", &LB, &UB);
    BIG = LB; END = UB; MID = (BIG+END)/2;
    while(BIG<=END && ITEM!=DATA[MID])
    {
        if(ITEM<DATA[MID]) END = DATA[MID-1];
        else BIG = DATA[MID+1];
        MID = BIG+END/2;
    }
    if(DATA[MID] == ITEM) printf("Item %d is on location %d\n", ITEM, MID);
    else printf("Item is not in Range.\n");
    return 0;
}
First input N = array element number.  ex. 8
Second input DATA[i] = input N element one by one must be SORTED. ex. 3 4 5 6 7 8 9 10
Third input ITEM = What I want to Search.  ex. 7
Forth input LB = From Which Index I Want to search.  ex. 2
Fifth input UB = Till Which Index I Want to search.  ex. 6
Output ex. Item 7 is on location 4


0 comments:

Post a Comment

Note: only a member of this blog may post a comment.