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 to find factorial using recursion

1 Ans How to Learn HTML - HyperText Markup Language easily? 

2 Ans Write a C program to implement Selection sort data structure and algorithm

2 Ans Train Location Message TR Train_Code and Send to 16318 Example: TR 705 Send to 16318

2 Ans Write a C program for Binary Search algorithm

1 Ans Write a C Program to check Anagrams of two strings

1 Ans Write a C program to print Floyd Triangle

1 Ans Write a C program to check Bubble sort data structure and algorithm

1 Ans Write a C program to reverse a number

1 Ans Write a C program to print Pascal Triangle