Binary Search [codingblocks]

Take as input N, the size of array. Take N more inputs and store that in an array. Take as input a number M. Write a function which returns the index on which M is found in the array, in case M is not found -1 is returned. Print the value returned.You can assume that the array is sorted, but you’ve to optimize the finding process. For an array of size 1024, you can make 10 comparisons at maximum.


1.It reads a number N.
2.Take Another N numbers as input in Ascending Order and store them in an Array.
3.Take Another number M as input and find that number in Array.
4.If the number M is found, index of M is returned else -1 is returned.Print the number returned.

Input Format
Constraints
N cannot be Negative. Range of Numbers N and M can be between -1000000000 to 1000000000

Output Format
Sample Input
5
3
5
6
9
78
6

Sample Output
2

Explanation
Array = {3, 5, 6, 9, 78}, target number = 6. Index of number 6 in the given array = 2. Write Binary search to find the number in given array as discuss in the class.


Java Code:



/*
Amit Kumar
04-12-2020
IDE Code: https://ide.geeksforgeeks.org/rX8ADrKL1r
*/

package array;
import java.util.Scanner;

public class Array_BinarySearch {
    public static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        int arrSize = scanner.nextInt();
        int [] arr = new int[arrSize];
        for (int i=0; i<arrSize; i++) {
            arr[i] = scanner.nextInt();
        }

        int searchElement = scanner.nextInt();
        System.out.println(binarySearch(arr, searchElement));
    }

    public static int binarySearch(int [] arr, int searchElement) {
        int start, end , mid;
        start = 0;
        end = arr.length-1;

        while (start<=end) {
            mid = (start + end)/2;
            if (arr[mid] == searchElement) {
                return mid;
            }

            if (arr[mid] > searchElement) {
                end = mid-1;
            } else {
                start = mid+1;
            }
        }
        return -1;
    }
}

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )