Computer Science, asked by Ashvi16, 1 year ago

WAP to input 10 numbers in ascending order in a 1D array and input a search value within the array list using binary search technique
(in java)

Answers

Answered by QGP
3
import java.util.*;
public class Binary_Search
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int i,j,z,lb=0,ub=9,p=0,k=0,n=0;
        int m[] = new int[10];
               
         System.out.println("Enter ten integers:");
         for (i=0;i<10;i++)
        {
            System.out.print("Enter integer: ");
            m[i] = in.nextInt();
        }
                for (i=0;i<9;i++)
        {
            for(j=0;j<(9-i);j++)
            {
                if(m[j]>m[j+1])
                {
                    z = m[j];
                    m[j] = m[j+1];
                    m[j+1] = z;
                }
            }
        }
                System.out.println();
                System.out.print("Enter the number to be search: ");
                n = in.nextInt();
                while(lb<=ub)
        {
            p = (lb+ub)/2;
            if (m[p]<n)
                lb = p+1;
            if (m[p]>n)
                ub = p-1;
            if (m[p]==n)
            {
                k=1;
                break;
            }
        }
                if (k==1)
            System.out.println("Given number exists in the array.");
                    else
            System.out.println("Given number does not exist in the array.");
   }
}

    

QGP: Binary Search works only when an array is sorted.
QGP: Assuming that the input integers wont always be in ascending order, I added the commands which sort the array
Ashvi16: okk....i understood
Answered by Aryangenius99999
2
the answer is here
hope it will help you
Attachments:
Similar questions