Write a function:
function solution(A);
that, given an array
A
of N
integers, returns the smallest positive integer (greater than 0) that does not occur in A
.
For example, given
A = [1, 3, 6, 4, 1, 2]
, the function should return 5.
Given
A = [1, 2, 3]
, the function should return 4.
Given
A = [−1, −3]
, the function should return 1.
Program code (in c++):
#include<iostream>
using namespace std;
int find_integer(int na,int a[])
{
int b[100],nb=0;
//Arranging array in ascending order
for(int i=0; i<na; i++)
{
for(int j=i+1; j<na; j++)
{
if(a[j] < a[i])
{
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
//Removing elements from an array which is either negative integer or zero
for(int i=0;i<na;i++)
{
if(a[i]<=0)
{
continue;
}
else{
b[i]=a[i];
nb=nb+1;
}
//cout<<b[i]<<endl;
}
//Removing duplicate/repeated integers from array
int temp[100];
int j = 0;
for (int i=0; i<nb-1; i++)
{
if (b[i] != b[i+1])
temp[j++] = b[i];
}
temp[j++] = b[nb-1];
// Modifying original array
for (int i=0; i<j; i++)
{
b[i] = temp[i];
}
//Finding the smallest integer not available in given array 'b'
if(nb==0)
{
int num=1;
return num;
}
else{
int finalnum=0;
int k=0;
int checknum=1;
int trace=0;
for(int i=0;i<nb;i++)
{
for(k=trace;k<nb;k++)
{
trace=k+1;
if(checknum==b[k])
{
finalnum=0;
break;
}
else{
finalnum=checknum;
goto l1;
}
}
checknum++;
}
l1: if(finalnum==0)
{
return checknum;
}
else
{
return finalnum;
}
}
}
int main()
{
int na,a[100],b[100],nb=0;
int get_result;
cout<<"Enter the size of array: ";
cin>>na;
for(int i=0;i<na;i++)
{
cout<<"Enter the elements of array: ";
cin>>a[i];
}
get_result=find_integer(na,a);
cout<<endl<<"The required smallest integer is : "<<get_result;
return 0;
}
Output