how to find all occurrences of a number in an array recursivelly
guys, given the fact I have an array how can I find all occurrences of the number recursively. I have figure out how to do a linear search recursively, but that would exit once it finds the number... what modification do I need to make in order to find all occurrences of the number.
Code :
int[] nums = {20, 25, 29, 55, 25}
//search with recursion
public static int search(int[] a, int n, int i)
{
if(i == a.length-1)
return -1;
else if(a[i] == n)
return i;
else
return search(a, n, ++i);
}
search(nums, 25, 0);
Re: how to find all occurrences of a number in an array recursivelly
Are you wanting to simply count them or return an array of all of their indexes?
Re: how to find all occurrences of a number in an array recursivelly
Re: how to find all occurrences of a number in an array recursivelly
thought about it for a bit, and came up with answer, may not be the most efficient. If someone got a better implementation.. post
Code :
static int count = 0, i = 0;
public static int displayOccu(int[] a, int n)
{
if(i == a.length)
return count;
else
{
if(a[i] == n)
{
i++;
count++;
return displayOccu(a, n);
}
else
{
i++;
return displayOccu(a, n);
}
}
}
Re: how to find all occurrences of a number in an array recursivelly
There is a much better way of doing it, by taking the count variable out. This should also do it:
Code java:
public static int displayOccu(int[] a, int n, int i)
{
if(i == a.length)
return 0;
else if(a[i] == n)
return 1+displayOcc(a,n,i+1);
else
return displayOcc(a,n,i+1);
}
This code is very similar to examples of summation with recursion. If the number is a hit, we add one and check the rest, otherwise we just check the rest. When it reaches the end of the array, it returns 0 to the previous call, and then adds together each 1 as the recursive call returns to where it was called.
I haven't compiled or tested the code, but in theory it should work.