1. You are given a number n, representing the size of array a.
2. You are given n numbers, representing elements of array a.Input Format
Asssumption - Array is sorted. Array may have duplicate values.
A number nOutput Format
n1
n2
.. n number of elements
A number d
A number representing first index
A number representing last index
Constraints
1 <= n <= 1000
1 <= n1, n2, .. n elements <= 100
1 <= d <= 100
Sample Input
15
1
5
10
15
22
33
33
33
33
33
40
42
55
66
77
33
Sample Output
5
9
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws Exception {
// write your code here
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] A = new int[n];
for(int i=0;i<n;i++)
A[i] =scn.nextInt();
int d = scn.nextInt();
System.out.println(binarySearch(0,n-1,A,d,true));
System.out.println(binarySearch(0,n-1,A,d,false));
}
public static int binarySearch(int lt, int rt,int[] A, int d, boolean findFirst){
int pos = -1;
while(lt<=rt){
int mid = (lt+rt)/2;
if(A[mid]<d)
lt = mid + 1;
else if(A[mid]>d)
rt = mid - 1;
else{
pos = mid;
if(findFirst)
rt = mid - 1;
else
lt = mid + 1;
}
}
return pos;
}
}
Comments
Post a Comment