In this technique, sorting takes place by stepping through all the elements one-by-one and comparing it with the adjacent element and swapping them if required.
It is known as bubble sort, because with every complete iteration the largest element in the given array, bubbles up towards the last place or the highest index, just like a water bubble rises up to the water surface.

Write a program to accept an array from the user and sort it. Ask the user for an element to search, apply binary search, and check if the element is present in the array or not. (Bubble sort+ Binary search program)

Check other java programs
https://java4school.com/count-no-of-palindrome-words-in-a-sentence(opens in a new tab)

import java.io.*;
class Binarysearch
{
    public static void main()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the length of the array");
        int len=Integer.parseInt(br.readLine());
        int arr[]=new int[len];
        int l=0,u=len-1,mid,p=0,temp;
        for(int i=0;i<len;i++)
        {
            System.out.println("Enter the elements of the array");
            arr[i]=Integer.parseInt(br.readLine());
        }
        for(int i=0;i<len-1;i++)
        {
            for(int j=i+1;j<len;j++)
            {
                if(arr[i]>arr[j])
                {
                    temp=arr[j];
                    arr[j]=arr[i];
                    arr[i]=temp;
                }
            }
        }
        
        System.out.println("The sorted array is");
        for(int i=0;i<len;i++)
        {
            System.out.println(arr[i]);
        }
        System.out.println("Enter the element that needss to be searched");
        int num=Integer.parseInt(br.readLine());
        while(l<=u)
        {
            mid=(l+u)/2;
            if(arr[mid]==num)
            {
                p=mid;
                break;
            }
            else if(num>arr[mid])
                l=mid+1;
            else
                u=mid-1;
        }
        if(p!=0)
            System.out.println("The element is at index no: "+p);
        else 
            System.out.println("The element cannot be found");
    }
}

Output:
Enter the length of the array
4
Enter the elements of the array
23
Enter the elements of the array
45
Enter the elements of the array
7
Enter the elements of the array
2
The sorted array is
2
7
23
45
Enter the element that needs to be searched
7
The element is at index no: 1

watch more java videos here
https://www.youtube.com/user/trushnatej

LEAVE A REPLY

Please enter your comment!
Please enter your name here