Computer Science, asked by Vaanika, 1 year ago

plz make the program of binary search using scanner class in notebook and give the pic.....
ans fast.........

Answers

Answered by butterflyqueen
4
import java.util.Scanner;

class BinarySearch
{
public static void main(String
args[])
{
int c, first, last, middle, n,
search, array[];

Scanner in = new
Scanner(System.in);
System.out.println("Enter
number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value
to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;

while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] ==
search )
{
System.out.println(search +
" found at location " + (middle
+ 1) + ".");
break;
}
else
last = middle - 1;

middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + "
isn't present in the list.\n");
}
}

butterflyqueen: Hope it helps you
Vaanika: thanks
butterflyqueen: welcome
Answered by Rajdeep11111
3
HELLO FRIEND!
Here's a program of Binary search in Java.

In the program, I am assuming that the array entered by the user is sorted.

Code:

import java.util.*;
class BinarySearch
{
public static void main (String args[])
{
Scanner sc = new Scanner (System.in);
int num[] = new int[10];
int ub = 9, lb = 0, mid, i, flag = 0;
System.out.println("Enter ten sorted numbers, one by one: ");
for (i = 0; i < 10; i++)
{
num[i] = sc.nextInt();
}
int ns;
System.out.print("Enter the number to be searched: ");
ns = sc.nextInt();
while (lb <= ub)
{
mid = (lb + ub)/2;
if (ns > num[mid])
{
lb = mid + 1;
}
if (ns < num[mid])
{
ub = mid - 1;
}
if (ns == num[mid])
{
flag = 1;
break;
}
}
if (flag == 1)
{
System.out.println("Search successful! The number is present!");
}
else
{
System.out.println("Search unsuccessful. The number is absent!");
}
}
}


BEST OF LUCK FOR YOUR EXAM.


Vaanika: thanks
Rajdeep11111: You are most welcome
butterflyqueen: welcome Vaanika
Similar questions