Find multiple missing elements unsorted in an unsorted array
class FindMultpleMissingElementsInAnArray {
int[] array;
boolean present[];
int low;
int high;
void printMissingElements() {
// Corner case
if(array.length == 0) {
System.out.println("Array is empty");
}
findLowAndHighElements();
createAndPopulateBooleanArray();
for(int i = 0; i < present.length; i++) {
if(present[i] == false) {
int missingElement = low + i;
System.out.println("Missing element is : " + missingElement);
}
}
}
void findLowAndHighElements() {
low = array[0];
high = array[0];
for(int i = 0; i < array.length; i++) {
// find highest element
if(array[i] > high) {
high = array[i];
}
// find lowest element
if(array[i] < low) {
low = array[i];
}
}
}
void createAndPopulateBooleanArray() {
System.out.println("High : " + high + ", Low : " + low);
present = new boolean[high - low + 1];
// If element is present in array then set present flag true
for(int i = 0; i < array.length; i++) {
present[array[i] - low] = true;
}
}
public static void main (String[] args) {
FindMultpleMissingElementsInAnArray obj = new FindMultpleMissingElementsInAnArray();
obj.array = new int[] {12,16,20,9,11,6,15,7,19,8,21};
obj.printMissingElements();
}
}
Comments
Post a Comment