Binary Search using Java

It is a technique to search an element in sorted array. In this type of search half of the array is ignored just after one comparison. Each time required element is compared with middle element of the array and range is decided .

Best Case Performance :  O(1)
Average Case Performance : O(log n)
Worst Case Performance : O(log n)


Demo Output:


The Program

import java.util.Scanner;

public class BinarySearch1
{
public static void main(String args[])
{
int i, first=0, last, mid, no, element;

Scanner s = new Scanner(System.in);

System.out.println("n How many elements:");
no= s.nextInt();
int arr[]= new int[no];

System.out.println("n Enter the elements:");
for (i = 0; i < no; i++)
arr[i] = s.nextInt();

System.out.println("n Enter the element to be searched:");
element = s.nextInt();

last = no - 1;
mid = (first + last)/2;

while( first <= last )
{
if ( arr[mid] < element )
first = mid + 1;
else
if ( arr[mid] == element )
{
System.out.println(element+" found...! " +"at position : t"+ (mid + 1));
break;
}
else
last = mid - 1;

mid = (first + last)/2;
}
if ( first > last )
System.out.println("Required element is not found in the list.n");
}
}

Found bugs, please do let me know by commenting here !

Bikash Panda
Catch Me On

Bikash Panda

Blogger / Embedded System Developer at WGLabz
A techie, tinkerer and tech lover, who loves to blog and feels everyone can learn tech provided they have the right attitude towards learning and passion. By profession, I am an IOT developer working in Smart Home/ Smart Grid domain.
Bikash Panda
Catch Me On

Latest posts by Bikash Panda (see all)

Related posts