adsense

Hii, welcome to my site. My name is Om prakash kartik. This blog helps you to learn programming languages concepts.

Program in C and C++ to find a given number using binary searching method

Program in C and C++ to find a given number using binary searching method

Note : Binary search method is always performed on sorted array. This searching method is faster than sequential searching method.


C PROGRAM
#include<stdio.h>
#include<conio.h>
#define size 35
void sort(int a[],int n)
 {
     int i,j,temp;
     for(i=0;i<n;i++)
     {
         for(j=0;j<n;j++)
         {
             if(a[i]>a[j])
             {
                 temp=a[i];
                 a[i]=a[j];
                 a[j]=temp;
             }
         }
     }
 }
void Bin_search(int A[],int n,int item) // Non Recursive function
 {
     sort(A,n);
     int i,mid,high,low;
     low=0;
     high=n-1;
     while(low<=high)
     {
         mid=(low+high)/2;
         if(A[mid]==item)
         {
             printf("\n%d is present.",item);
             return;
         }
         else if(A[mid]>item)
            low=mid+1;
         else
             high=mid-1;
     }
     printf("\n%d is not present.",item);
 }
 int main()
  {
      int a[size],i,n,d;
      printf("Enter the size of the array:-");
      scanf("%d",&n);
      printf("Enter %d numbers:-",n);
      for(i=0;i<n;i++)
        scanf("%d",&a[i]);
      for(i=0;i<n;i++)
        printf("%4d",a[i]);
      printf("\nEnter a number which you want to search:-");
      scanf("%d",&d);
      Bin_search(a,n,d);

      getch();
  }

C++ PROGRAM
#include<iostream>
#include<conio.h>
using namespace std;
const int size=25;
void sort(int a[],int n)
 {
     int i,j,temp;
     for(i=0;i<n;i++)
     {
         for(j=0;j<n;j++)
         {
             if(a[i]>a[j])
             {
                 temp=a[i];
                 a[i]=a[j];
                 a[j]=temp;
             }
         }
     }
 }
void Bin_search(int A[],int n,int item) // Non Recursive function
 {
     sort(A,n);
     int i,mid,high,low;
     low=0;
     high=n-1;
     while(low<=high)
     {
         mid=(low+high)/2;
         if(A[mid]==item)
         {
             cout<<endl<<item<<" is present.";
             return;
         }
         else if(A[mid]>item)
            low=mid+1;
         else
             high=mid-1;
     }
     cout<<endl<<item<<" is not present.";
 }
 int main()
  {
      int a[size],i,n;
      cout<<"Enter the size of the array:-";
      cin>>n;
      cout<<"Enter "<<n<<" numbers:-";
      for(i=0;i<n;i++)
        cin>>a[i];
      for(i=0;i<n;i++)
        cout<<" "<<a[i];
      int d;
      cout<<"\nEnter a number which you want to search:-";
      cin>>d;
      Bin_search(a,n,d);
      getch();
  }

Output :-













Related programs

  •      Program in C and C++ to find a given number using binary searching method(Recursive function)

Post a Comment

0 Comments