0% found this document useful (0 votes)
2 views

Binary Search

The document contains a Java program that implements a binary search algorithm. It prompts the user to input the size of an array, the elements of the array, and a value to search for. The program then searches for the value using binary search and outputs the index if found or a message if not found.

Uploaded by

Rig Baitha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Binary Search

The document contains a Java program that implements a binary search algorithm. It prompts the user to input the size of an array, the elements of the array, and a value to search for. The program then searches for the value using binary search and outputs the index if found or a message if not found.

Uploaded by

Rig Baitha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Binary search

import java.util.*;
class BinarySearch
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the index of array”);
int n = sc.nextInt();
int arr[] = new int[n];

int i, first, last, mid, key;

System.out.println(“Enter the elements of array”);


for(i=0; i<n; i++)
{
arr[i] = sc.nextInt();
}

System.out.println(“Enter the value to search”);


key = sc.nextInt;

mid = (first + last)/2;


while( first <= last )
{
if ( arr[mid] == key )
{
System.out.println("Element is found at index: " + mid);
break;
}
else if ( arr[mid] < key )
{
first = mid + 1;
}
else
{
last = mid - 1;
}
mid = (first + last)/2;
}

if ( first > last )


{
System.out.println("Element is not found!");
}
}
}

You might also like