KnowledgeBoat Logo
|

Computer Applications

Write a program to search for 66 and 71 in the following array :

304172113184295456717878899931096119912\underset{0}{\boxed{3}}\underset{1}{\boxed{4}}\underset{2}{\boxed{7}}\underset{3}{\boxed{11}}\underset{4}{\boxed{18}}\underset{5}{\boxed{29}}\underset{6}{\boxed{45}}\underset{7}{\boxed{71}}\underset{8}{\boxed{87}}\underset{9}{\boxed{89}}\underset{10}{\boxed{93}}\underset{11}{\boxed{96}}\underset{12}{\boxed{99}}

Make use of binary search technique. Also give the intermediate results while executing this algorithm.

Java

Java Arrays

5 Likes

Answer

public class KboatBinarySearch
{
    public int binSearch(int arr[], int item)    {
        int l = 0, index = -1;
        int h = arr.length - 1;

        System.out.println("Searching for " + item);
        while (l <= h) {
            int m = (l + h) / 2;
            System.out.println("Searching in sub-array :");
            for(int i = l; i < h; i++)
                System.out.print(arr[i] + " ");
            
            System.out.println();
            
            System.out.println("Comparing " + item + " with "
                                + arr[m] + " at index " + m);
            
            if (arr[m] < item)
                l = m + 1;
            else if (arr[m] > item)
                h = m - 1;
            else {
                index = m;
                break;
            }
        }
        return index;
    }
    
    public static void main(String args[]) {
        KboatBinarySearch obj = new KboatBinarySearch();
        
        int X[] = {3, 4, 7, 11, 18, 29, 45, 71, 87, 89, 93, 96, 99};
        
        int index = obj.binSearch(X, 66);
        if (index == -1) {
            System.out.println("66 not found");
        }
        else {
            System.out.println("66 found at index " + index);
        }
        
        index = obj.binSearch(X, 71);
        if (index == -1) {
            System.out.println("71 not found");
        }
        else {
            System.out.println("71 found at index " + index);
        }
        
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program to search for 66 and 71 in the following array : Make use of binary search technique. Also give the intermediate results while executing this algorithm.

Answered By

1 Like


Related Questions