Breaking

Wednesday, April 17, 2019

Program no: 8(D) C Program for Binary Searching in an Array

C program for Binary Searching in an Array

Binary Search in C

To perform binary search in C programming, you have to ask to the user to enter the array size then ask to enter the array elements. Now ask to enter an element to be search, to start searching that element using binary search technique

C Programming Code for Binary Search

Following C program first ask to the user to enter "how many element he/she want to store in the array", then ask to enter the array element one by one". After storing the element in the array, program ask to enter the element which he/she want to search in the array whether the number/element is present or not in the given array. The searching technique used here is binary search which is fast technique:

Source Code:
/*
Summary: Binary search compares the search value with the value of the middle element of the array. If they match, then a matching element has been found and its position is returned. Otherwise, if the search value is less than the middle element's value, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search value is greater, on the sub-array to the right.
Complexity - O(log n)
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<stdio.h>
 int main()
{
    int arr[50],i,n,x,flag=0,first,last,mid;
     printf("Enter size of array:");
    scanf("%d",&n);
    printf("\nEnter array element(ascending order)\n");
     for(i=0;i<n;++i)
        scanf("%d",&arr[i]);
      printf("\nEnter the element to search:");
    scanf("%d",&x);
      first=0;
    last=n-1;
      while(first<=last)
    {
        mid=(first+last)/2;
         if(x==arr[mid])
{
            flag=1;
            break;
        }
        else
            if(x>arr[mid])
                first=mid+1;
            else
                last=mid-1;
    }
     if(flag==1)
        printf("\nElement found at position %d",mid+1);
    else
        printf("\nElement not found");
     return 0;
}

No comments:

Post a Comment

Popular Posts

Post Top Ad

Your Ad Spot

Pages