(7 marks) Create a void method called my_reverse with the following signature: p
ID: 3905777 • Letter: #
Question
(7 marks) Create a void method called my_reverse with the following signature:
public static void my_reverse(int[] arr, int start, int end)
Your method should reverse the elements of the sub-array from indexes start to end, inclusive. No need to create a new array, just modify the array that was passed in. You may not use any existing reverse() functionality in the Java library. You must implement the reversal yourself.
For example: If the array is {2, 4, 6, 5, 3}, and you call my_reverse(array, 1, 3), The new ordering of the array should be: {2, 5, 6, 4, 3}
An iterative solution will earn a maximum of 5 marks. To achieve the full 7 marks, your solution must be recursive. If the indexes are invalid in any way, do nothing to the array.
Explanation / Answer
Recursive functions are those functions which call themselves with different parameters in every call. They should always have a bound check where the recursion will break otherwise the functions will be called infinitely.
The following method calls the same method with the start index after increasing by 1 and end index after decreasing by 1 and breaks when start >= end or value of start or end is invalid. This means we call my_reverse() with the sub array of 2 less elements and then we swap the start and end indices elements. For my_reverse(arr, 1, 3), my_reverse(arr, 2, 2) is called. In my_reverse(arr, 2, 2), as 2 >= 2, it returns without calling any other function and back in my_reverse(arr, 1, 3), arr[1] and arr[3] are swapped and then control is returned to main(). You can do it in your notebook for better understanding and to avoid confusion.
public static void my_reverse(int[] arr, int start, int end)
{
//Return to parent function, if start or end value is invalid
if(start < 0 || start > arr.length - 1 || end < 0 || end > arr.length - 1)
return;
//Return to parent function if start is equal or greater than end
if(start >= end)
return;
//Following statements will only run if both the above conditions are false
//Call my_reverse() with same array, increased start and decreased end
my_reverse(arr, start + 1, end - 1);
//Swap arr[start] and arr[end]
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
The function definition is thoroughly checked for different valid and invalid test cases.
Kindly give a thumbs up, if found useful. Comment for queries. :)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.