Java Binary search code with occurrence idx return
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 6, 6, 7 ,8 ,9};
int target = 11;
int[] indices = new int[array.length] ;
int count = 0;
int low =0, high = array.length-1;
while(low <= high ) {
int mid = low+(high-low)/2;
if(array[mid] == target) {
for (int i = mid; i >= 0 && array[i] == target;i-- ) {
indices[count++] = i;
}
for (int i = mid+1; i < array.length && array[i] == target; i++) {
indices[count++] = i;
}
break;
}
else if ( array[mid] > target) {
high = mid-1;
}
else
low = mid+1;
}
if (count!=0) {
System.out.print("Target is found at: ");
for(int i = 0; i< count;i++) {
System.out.print(indices[i]+" ");
}
}
else System.out.print("Target not found.");
}
HashMap
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Main{
public static void main(String[] args) {
HashMap<String, Double> map = new HashMap<>();
map.put("Minju", 3.71); // adds a new pair if it didn't exist b4
map.put("Poushi", 3.65); // updates values if key is same
map.put("Nishat", 3.82); // add as new pair id value is same
map.put("A", 3.45);
System.out.println(map);
System.out.println(map.containsKey("Minju"));
System.out.println(map.containsValue(3.65));
System.out.println(map.get("Minju")); // get(key) -> returns valur of that key
System.out.println();
//getting pairs using iterator
for ( Map.Entry<String, Double> e : map.entrySet() ) {
System.out.println(e.getKey() + " "+ e.getValue());
}
System.out.println();
// using a set of keys
Set<String> keys = map.keySet();
for (String key: keys) {
System.out.println(key +" "+ map.get(key));
}
map.remove("A"); // remove using key
System.out.println(map.size()); //returns the number of (key, value) pairs
}
}