Binary search in java with bubble sort

Binary Search in java with Bubble sort

Binary search in java with bubble sort 

Binary Search with Bubble sort program has been defining as follows. First, we have taken 10 elements in the array name[] and then perform the bubble sort. After sorting we have done binary sort.

What is Binary search?

Binary search is a search algorithm that is faster than linear search and the time the complexity of the above algorithm is O(n). In this search, data must be in sorted order and it perform divide the array length by 2 and find the middle value and if the middle value less than the search value then it performs towards array lesser value till it finds the match and if the search element greater the middle value then it performs a search towards the array’s upper part of its mid value.

Java program is as follows   

import java.io.*;

public class BinarySearchWithSorting

{

    public static void main(String args[]) throws IOException

    {

        String name[] = new String[20];

        String s, t;

        int i,f=0,j;

        int low, high, mid, pos;

        InputStreamReader in=new InputStreamReader(System.in);

        BufferedReader br=new BufferedReader(in);

        System.out.println("Enter 10 Names in array:");

        for(i=0;i<10;i++)

        {

            name[i] = br.readLine();

        }

        System.out.println("Enter name to Search:");

        s = br.readLine();

        // Bubble Sorting of array

        for(i=0;i<9;i++)

        {

            for(j=0;j<9-i;j++)

            {

                if(name[j].compareTo(name[j+1])>0)

                {

                    t = name[j];

                    name[j] = name[j+1];

                    name[j+1] = t;

                }

            }

        } // end of sorting

        System.out.println ("Sorted array :");

        for(i=0;i<10;i++)

        {

            System.out.print (name[i] + " ");

        }

        // Binary Search

        high = 10;

        low = 0;

        pos = 0;

        while(low <= high)

        {

            mid = (low + high) / 2;

            if(s.compareTo(name[mid])<0)

            {

                high = mid - 1;

            }

            else if(s.compareTo(name[mid])>0)

            {

                low = mid + 1;

            }

            else if(s.compareTo(name[mid])==0)

            {

                pos = mid + 1;

                break;

            }

        }

        System.out.println("\n Search result");

        System.out.println(s+" is located at " + pos);

    }

}

Output

Enter 10 Names in the array:

Ramesh

Akbar

Sunil

Binay

Cindy

Umesh

Junaid

Danny

Kalim

Nagma

Enter name to Search:

Sunil

Sorted array:

Akbar Binay Cindy Danny Junaid Kalim Nagma Ramesh Sunil Umesh

 Search result

Sunil is located at 9


More Java programs 

 


SHARE THIS
Previous Post
Next Post