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?
You are assigning mid=n-1; instead of high=n-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*/;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With