So in the programming course I'm taking we learned about recursion. I got an assignment to write recursive function that gets sorted array and a number and return the index of that number in the array if existed.
I didn't quite understand yet the subject of recursion so I need a little help with my code. I think i'm at the right direction but again, I'm a little struggling with the subject so I thought I could find guidance and help here.
this is the code I have at the moment:
private static int arrayIndexValue(int[] arr, int ind)
{
if (ind > arr.Length/2)
{
return arrayIndexValue(arr.Length/2, ind)
}
else if (ind < arr.Length/2)
{
return arrayIndexValue(arr.Length/2)
}
}
basically what i wanted to write here is something like this:
if the number the user inserts is smaller then the middle of the array, continue with the function but with the array cut in half (Binary search)
same if the number is bigger (i suggested to use my function with something like the binary search but as you can see i dont quite know how to apply it to my code)
i got an assignment to write recursive function that gets sorted array and a number and return the index of that number in the array if existed.
In your method you check indexes, not values - you should compare values of elements, not indexes.
To write recursive function to find element you should pass array, element to find, start index and end index. Start index and end index will be used for finding in part of array.
Your method will be something like this:
private static int GetIndex(int[] arr, int element, int startIndex, int endIndex)
{
if (startIndex > endIndex)
{
return -1; //not found
}
var middleIndex = (startIndex + endIndex) / 2;
if (element == arr[middleIndex])
{
return middleIndex;
}
if (element < arr[middleIndex])
{
return GetIndex(arr, element, startIndex, middleIndex - 1);
}
else
{
return GetIndex(arr, element, middleIndex + 1, endIndex);
}
}
and to get some index:
static void Main(String[] args)
{
var arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var element = 5;
var index = GetIndex(arr, element , 0, arr.Length - 1);
}