# Binary Search to find element in array using Java

This tutorial will focus on**, How to find an element in an array using Binary Search in Java**

Hey folks,

I am back with another tutorial for you. In this tutorial, we will learn how to find an element using Binary Search in Java. As you must have realized how important is searching in **competitive programming**. If I say it more clearly then you runtime is determined by search algorithm.

**Binary Search** has better time complexity **O(log(n))** as compared to other search algorithms. Now let’s come to the logic of our program. In binary search we take three variables namely low, high and mid. We keep two pointers at either side of our array namely low at first element and high at last.

## Binary Search in an array in Java

We bring pointer of mid repeatedly to middle of our array. And compare with our target element. If our target element is less than element at mid. We shift our high pointer just to one position left of our mid value.

If our target element is greater than element at mid. We shift our low pointer just to one position right of our mid value.

And this process is performed repeatedly till the value of low is less than or equal to high.

**Create BinarySearch.java file**

### Java code to Find an element in an array using Binary search

public class BinarySearch { public int binarySearch(int arr[],int target) { int lo=0; int hi=arr.length-1; int mid; while(lo<=hi) { mid=(lo+hi)/2; if(arr[mid]<target) { lo=mid+1; } else if(arr[mid]>target) { hi=mid-1; } else { return mid; } } return -1; } }

**Create Runner.java file**

public class Runner { public static void main(String[] args) { BinarySearch bs= new BinarySearch(); int arr[]= {2,3,4,5,6,7}; int x=4; int index=bs.binarySearch(arr,x); if(index==(-1)) System.out.println("Element not found"); else System.out.println("Element is found at index " + index); } }

We have created **Runner.java** so that it’s easy for you to understand and differentiate how the code is working. If you want you can create both in a single file.

In runner file, we make an object named bs of BinarySearch so as to connect the two files while compiling. And in the next line, we have called our function named binarySearch which we made in file** BinarySearch.java.**

In Java, we call a function with the help of object like **object.functionName**. If the above function returns some index value we display element is found.

If you still have doubt in understanding the code do ask in the comment below.

You may also read,

## Leave a Reply