Find the smallest positive number missing from an unsorted array | Set 1 | C ++ program for the above approach ; Function for finding the first missing positive number ; Loop to traverse the whole array ; Loop to check boundary condition and for swapping ; Checking any element which is not equal to i + 1 ; Nothing is present return last index ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int firstMissingPositive ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { while ( arr [ i ] >= 1 && arr [ i ] <= n && arr [ i ] != arr [ arr [ i ] - 1 ] ) { swap ( arr [ i ] , arr [ arr [ i ] - 1 ] ) ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != i + 1 ) { return i + 1 ; } } return n + 1 ; } int main ( ) { int arr [ ] = { 2 , 3 , -7 , 6 , 8 , 1 , -10 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int ans = firstMissingPositive ( arr , n ) ; cout << ans ; return 0 ; }