28. write a program in java to input an array of 10 numeric elements and sort it in ascending order. accept a value from the user and using binary search find out the cell position the number occupies in the array. the program must also print appropriate message for unseccesful search.
Answers
Answer:
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int a[]=new int[10];
int temp=0,ns=0,lb=0,ub=9,p=0,pos=0,f=0;
System.out.println("Enter the elements of the array");
for(int i=0;i<a.length;i++)
{
a[i]=in.nextInt();
}
System.out.println("Given array:"+Arrays.toString(a));
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a.length-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("Array sorted successfully");
System.out.println("Sorted Array:"+Arrays.toString(a));
System.out.println("Binary Search added successfully");
System.out.println("Enter the number to be searched");
ns=in.nextInt();
for(int i=0;i<a.length;i++)
{
p=(lb+ub)/2;
if(a[p]<ns)
lb=p+1;
if(a[p]>ns)
ub=p-1;
if(a[p]==ns)
{
pos=p;
f=1;
break;
}
}
if(f==1)
System.out.println("Search successful the element is found in index "+pos);
else
System.out.println("Search unsuccessful the element is not found at any position");
in.close();
}
}
If you want the exact position just add pos=p+1;
Output is attched.