This is the Java Program to Find the Smallest Positive Integer Missing in an Unsorted Integer Array.
Given an array of integers, find out the smallest positive integer missing from the array.
Example:
Array = [-1, -3, 3, 2, 8 ,6]
Output: 1.
First sort the array. Then initialize a variable to 1 and using a loop scan through the array. Check the value of the variable if it matches the current array element, increment it if that is the case. The value of the variable after the loop is the smallest positive missing integer.
Here is the source code of the Java Program to Find the Smallest Positive Integer Missing in an Unsorted Integer Array. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Find the Smallest Positive Integer Missing in
//an Unsorted Integer Array
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SmallestPositiveInteger {
// Function to find the smallest positive missing integer
static int findSmallestPositiveMissingInteger(int[] array){
Arrays.sort(array);
int j,i = 1;
for(j = 0; j<array.length; j++){
if(array[j] == i){
i++;
}
}
return i;
}
// Function to read input and display the output
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int size;
System.out.println("Enter the size of the array");
try {
size = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("Invalid Input");
return;
}
int[] array = new int[size];
System.out.println("Enter array elements");
int i;
for (i = 0; i < array.length; i++) {
try {
array[i] = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("An error occurred");
return;
}
}
int missing = findSmallestPositiveMissingInteger(array);
System.out.println("The smallest positive missing integer is " + missing);
}
}
1. In function findSmallestPositiveMissingInteger, firstly the array is sorted.
2. Then, the loop for(j = 0; j<array.length; j++) traverses the array to find the smallest positive missing integer.
3. Finally, the smallest positive missing integer i is returned.
Time Complexity: O(n*(log(n)) ) where n is the number of elements in the array.
Case 1 (Simple Test Case): Enter the size of the array 6 Enter array elements -1 -3 3 2 8 6 The smallest positive missing integer is 1 Case 2 (Simple Test Case - another example): Enter the size of the array 5 Enter array elements -1 -2 -3 -4 -5 The smallest positive missing integer is 1
Sanfoundry Global Education & Learning Series – Java Programs.
If you find any mistake above, kindly email to [email protected]
- Practice BCA MCQs
- Check Java Books
- Practice Programming MCQs
- Check Programming Books
- Apply for Java Internship