C Progamming help

SMDG

Member
Dec 19, 2022
3
1
3
#include<stdio.h>

int bSearch(int A[],int low,int high,int searchKey)
{

int position=-1;
int found=0;
int mid;

while(low<=high && !found)
{
mid=(low+high)/2;
if(A[mid]==searchKey)
{
position=mid;
found=1;
}
else if(searchKey<A[mid])
{
low=mid-1;
}
else
{
high=mid+1;
}
}
return position;
}

int main()
{
int arr1[]={5,12,23,28,35,42};

int key=35;
int position=bSearch(arr1,0,5,key);
if(position==-1)
{
printf("Element is not present");
}
else
{
printf("Element is present in index %d",position);
}
}

binary search algorithm ekk code ekak thiyenne. meka run karama run time error ekak enw.mokadda meke thiyena waradda. pls help brothers!

p.s- run time error-SIGTSTP
codeblocks wala tamai run kare
 
Last edited:
  • Like
Reactions: kinkon

හෙළයෙක්

Well-known member
  • Apr 26, 2014
    48,460
    98,391
    113

    How to Ask Programming Questions

    https://www.propublica.org/nerds/how-to-ask-programming-questions

    2. Be specific


    When asking your question, be specific. This means your post should include:
    • The tools you’re using, including version numbers and your operating system version.
    • What you’re trying to accomplish – what did you expect to happen if everything had worked?
    • The code you’re using (or just the relevant parts)
    • Any error messages you got
    • What you’ve tried already, and what happened
     
    • Like
    Reactions: Gwynbleidd and SMDG

    EKGuest

    Well-known member
  • Nov 16, 2022
    3,206
    5,703
    113
    Error එක එන්නේ if...else එක ඇතුලේ mid value එක සෙට් කරනකොට high low මාරු කරලා දාලා තියෙන නිසා. තව ඔතන found වේරියබල් එක අත්‍යාවශ්‍ය නැහැ while loop එක ඇතුලේ searchKey එක හම්බුන ගමන් break කලාම හරි.

    C:
    #include<stdio.h>
    
    int bSearch(int A[],int low,int high,int searchKey)
    {
        int position=-1;
        int found=0;
        int mid;
    
        while(low<=high && !found)
        {
            mid=(low+high) / 2;
            if(A[mid]==searchKey)
            {
                position=mid;
                found=1; // found වේරියබල් එක පාවිච්චි නොකර මෙතන break කරලා ලූප් එකෙන් exit වෙන්න පුලුවන්
            }
            else if(searchKey<A[mid])
            {
                high=mid - 1;
            }
            else
            {
                low=mid + 1;
            }
        }
       
        return position;
    }
    
    int main()
    {
        int arr1[]={5,12,23,28,35,42};
    
        int key=35;
        int position= bSearch(arr1,0,5,key);
       
        if(position==-1)
        {
            printf("Element is not present");
        }
        else
        {
            printf("Element is present in index %d",position);
        }
    }
     
    Last edited:
    • Like
    • Love
    Reactions: SMDG and Gwynbleidd