Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Binary search program giving an error?

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?

like image 998
Green Noob Avatar asked Apr 30 '26 16:04

Green Noob


2 Answers

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

like image 87
Sergey Kalinichenko Avatar answered May 03 '26 06:05

Sergey Kalinichenko


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*/;
like image 34
Luchian Grigore Avatar answered May 03 '26 06:05

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!