find out all the elements in a sorted integer array whose value is equal to index of the array

#include <stdio.h>

int searchindex(int a[], int minindex, int maxindex, int ret[], int index)
{
if(minindex > maxindex )
return index;

int mid = (minindex + maxindex) / 2;

if(mid == a[mid])
{
ret[index++] = mid;
index = searchindex(a, mid+1, maxindex, ret, index);
index = searchindex(a, minindex, mid-1, ret, index);

return index;
}
else if(mid < a[mid])
maxindex = mid - 1;
else
minindex = mid + 1;

return searchindex(a, minindex, maxindex, ret, index);

}


int main()
{
int n;

scanf("%d", &n);

int a[n];

int i;


for(i = 0; i < n; ++i)
scanf("%d", a + i);

int ret[n];

int index = searchindex(a, 0, n - 1, ret, 0);

for(i = 0; i < index; ++i)
printf("%d ", ret[i]);

printf("\n");
}
Advertisements

2 thoughts on “find out all the elements in a sorted integer array whose value is equal to index of the array

  1. I do not think it will list all the elements whose value is equal to the index as the code returns once it finds the first element equal to the index. May be I am missing something here but the code is different from the problem statement, at least, it appears to me so.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s