Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a binary search program in C Language. Write a function called binary_sear

ID: 3570007 • Letter: W

Question

Write a binary search program in C Language.

Write a function called binary_search().

Input: a list of n sorted integer values and a target value

Output: True if target value exists in list and location of target value, false otherwise

Method:

-Set left to 1 and right to n

-Set found to false

-Set targetindex to -1

-While found is false and left is less than or equal to right

--Set mid to midpoint between left and right

--If target = item at mid then set found to true and set targetindex to mid

--If target < item then set right to mid

Explanation / Answer

#include<stdio.h>

int main(){

    int a[10],i,n,m,c,l,u;

    printf("Enter the size of an array: ");

    scanf("%d",&n);

    printf("Enter the elements of the array: " );

    for(i=0;i<n;i++){

         scanf("%d",&a[i]);

    }

    printf("Enter the number to be search: ");

    scanf("%d",&m);

    l=0,u=n-1;

    c=binary(a,n,m,l,u);

    if(c==0)

         printf("Number is not found.");

    else

        

    return 0;

}

int binary(int a[],int n,int m,int l,int u){

    int mid,c=0;

    if(l<=u){

         mid=(l+u)/2;

         if(m==a[mid]){

             c=1;

         }

         else if(m<a[mid]){

             return binary(a,n,m,l,mid-1);

         }

         else

             return binary(a,n,m,mid+1,u);

    }

    else

       return c;

}

Sample output:

Enter the size of an array: 5

Enter the elements of the array: 8 9 10 11 12

Enter the number to be search: 8

8 is found at location 1.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote