Ask Question - Get Answer

2 Ans Write a C program for Binary Search algorithm

Asked by AL MaMun (4 Golds) Friday, 31 Jul 2020, 04:55 PM at (Education Tutorials)

Please log in to answer, like and save
0
Save 0

<<< Previous
Log in to Answer Next >>>

Answer(s):

#include<bits/stdc++.h>

int action(int A[], int n, int x)

{

    int left, right, mid;

    left = 0;

    right = n-1;

    while(left <= right)

    {

        mid = (left + right)/2;

        if(A[mid] == x)

            return mid;

        if(x > A[mid])

            left = mid + 1;

        else

            right = mid - 1;

    }

    return -1;

}

int main()

{

    int a[10] = {1, 3, 5, 9, 12};

    /// array must be sorted

    int r = action(a, 5, 12);

    if(r!=-1)

        printf("Found");

    else

        printf("Not Found");

    return 0;

}


Answered by Birds of the sky (2 Golds) Saturday, 25 Dec 2021, 11:31 AM

Please log in to Upvote, Downvote and Report

C Program of Binary search algorithm :


#include<iostream>

using namespace std;

int main()

{

    int a[1000], beg, end, mid, i, n, s;

    cout<<"Enter n\n";

    cin>>n;

    cout<<"Enter Number (small to big sorted must)\n";

    for(i=1; i<=n; i++)

    {

        cin>>a[i];

    }

    cout<<"What search?\n";

    cin>>s;

    beg=1;

    end=n;

    mid=(beg+end)/2;

    while(beg<=end && a[mid]!=s)

    {

        if(a[mid]<s)

            beg=mid+1;

        else

            beg=mid-1;

        mid=(beg+end)/2;

    }

    if(a[mid]==s)

        cout<<"Data Found at "<<mid<<" position\n";

    else

        cout<<"Data not found";

     return 0;

}


Answered by AL MaMun (4 Golds) Friday, 31 Jul 2020, 04:56 PM

Please log in to Upvote, Downvote and Report
           

Related Q/A:

1 Ans Write a C program for Interest Calculation

1 Ans The general rules for constructing names for variables (unique identifiers)

2 Ans BPSC Programming Aptitude Lab Test Important programs

1 Ans Bank Exam all important Writing Materials

2 Ans Write a C program for Binary Search algorithm

1 Ans A C Program to split a number into digits

3 Ans BPSC Assistant Programmer Lab Aptitude test Programs and Queries with Proper solution (Taken By BCC)

1 Ans A Quest for Peace in the Middle East: Recent Perspectives - composition

1 Ans Write a C program to print Fibonacci number series

1 Ans Write a C program to check a Prime number