I have an array e.g. {1,2,4,5,6}. I want my function to find biggest possible number X such that all numbers from 1,2,...,X-1 are in the array. In this case X=3. Numbers in an array could be from 0 to infinitty.
My attempt is:
int array(int* t, int r) {
int* a;
int m=0;
int i;
for(i=0;i<=r;i++){
a[i]=i;
if(a[i]==t[i])
m++;
}
return m;
}
I wanted to create an array from 1 to r, which is the length of an array, full of natural number i.e. {1,2,3...} . Then i wanted to compare it with the actual array t. If there is a match look for another one.
I have no idea why it does not work and how to fix it?
Anyway code does not work and i still have no idea how to fix this.
Still looking for an answer.
Update: I did something like:
int array(int* t, int r) {
for(int x=0;x<r;x++){
for(int y=0; y<r-1;y++){
if(t[y]>t[y+1]){
int temp=t[y+1];
t[y+1]=t[y];
t[y]=temp;
}
}
}
for (int i = 0; i != r; i++) {
if (t[i] != (i + 1)) {
return i + 1;
}
}
return r + 1;
}
However when in input array i have zero at some place e.g. {5,0,1,2} the function always, regardless of where the zero is placed returns 1. Why is that?