# Best C Programming code for Binary Search using pointer(February,2021)

## Best C Programming code for Binary Search using pointer(February,2021)

**Introduction**

This blog is completely dedicated for implementing Binary Search technique. When we have a list of elements and if we like to search any element, we will use this technique.

**Pre-requisite**

Before starting Binary Search , the list of elements must be sorted. Because Binary search logic can only work on sorted list. Before entering into Binary search logic, you can use any sorting algorithm. Here I have followed Bubble sort.

**Explanation**

In this searching technique, first of all the complete element list is divided into halves and from those halves, depending upon the condition program will select proper half. I have used pointer concept for both sorting and searching as well. The code is very easy to understand. In this code I have used separate function for Bubble Sort.

I hope that this code will help you to understand the Binary Search technique very easily. If anyone have any doubt please feel free to contact me through email id : creativeresource2020@gmail.com.

You also can put your valuable comment in the comment section.

You also can visit my Youtube channel :

https://www.youtube.com/channel/UC51-9SUu0-CaAYwT4XLNtSw

#include<stdio.h> int binsear(int *,int,int); int bubble(int *,int); int main() { int ar[50],m,i,n,p; printf("\nEnter the number of elements : "); scanf("%d",&m); printf("\nEnter the values : "); for(i=0;i<m;i++) scanf("%d",&ar[i]); printf("\nEnter the value you wanna search : "); scanf("%d",&n); bubble(ar,m); if(binsear(ar,m,n))//1/non zero = true 0 = false printf("\nFound"); else printf("\nNot Found"); } int binsear(int *ptr,int p,int q) { int lb=0,ub=p-1,mid; while(lb<=ub) { mid=(lb+ub)/2; if(*(ptr+mid)== q) return 1; else if(*(ptr+mid)>q) ub=mid-1; else lb=mid+1; } return 0; } int bubble(int *ptr,int m) { int i,j,temp; for(i=0;i<m;i++) { for(j=0;j<m-i-1;j++) { if(*(ptr+j)>*(ptr+j+1))//if(ar[j]>ar[j+1]) { temp=*(ptr+j); //temp=ar[j]; *(ptr+j)=*(ptr+j+1); //ar[j]=ar[j+1] *(ptr+j+1)=temp; //ar[j+1]=temp } } } }