3

I wrote the following program for conducting Binary search on an array when the elements are entered in ascending order.

#include<stdio.h>
#include<conio.h>

void main()
{
    int key,high,low,mid,n,i,a[100];

    clrscr();

    printf("Enter the number of elements:");
    scanf("%d",&n);

    printf("\nEnter the elements:\n");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    printf("Enter the key element:");
    scanf("%d",&key);

    low=0;
    mid=n-1;
    mid=(low+high)/2;
    while(low <= high && key != a[mid])
    {
        mid=(low+high)/2;
        if (key > a[mid])
            low=mid+1;
        else
            high=mid-1;
    }

    if (a[mid] == key)
        printf("\nKey element is present at position %d",mid+1);
    else
        printf("\nElement not present.");
    getch();
}

When I ran the compiled program in Dev C++, I got a 'Memory could not be read' error. How can this be corrected?

0

5 Answers 5

4

You are assigning mid=n-1; instead of high=n-1;.

Sign up to request clarification or add additional context in comments.

Comments

1

You failed to initialize high, so you're using some garbage in mid=(low+high)/2;

You probably want to initialize it along low:

low=0;
high=/*whatever*/;

Comments

0

This:

 mid=n-1;
 mid=(low+high)/2;

should probably be:

 high = n-1;
 mid = (low+high)/2;

Notice how you mistakenly write to mid twice, instead of initializing high. Also notice that a proper binary search is quite hard to get right, there are nasty overflow conditions for large arrays.

Comments

0

Typo, just replace mid=n-1; with high=n-1;.

Comments

0

The problem lies on the statement:

mid=n-1;

This should be changed to:

high=n-1;

Because you are just including high variable which is not initialized. This also would result in you using garbage in the rest of your code. Mid=n-1 would lead to a logical error.

Always make sure that you initialize the variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.