PA6_Recurrence

# 2 1 2 3 4 5 what the original array looked like

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: at the original array looked like public void reverse(int originalArray, int low, int high) 4 3 And again... 2 1 2 3 4 5 What the original array looked like public void reverse(int originalArray, int low, int high) 5 4 3 2 1 Now we have all the elements from the original array in reversed order. Since we changed the values in the actual array, we are finished. Nothing to return. public int reverse(int originalArray) •  Another way to recursively reverse an array •  Base case: there is 1 or 0 elements •  Writing into a new array instead of swapping values in place •  Useful if you needed both the original and the sorted version to be separate 1 2 3 4 5 public int reverse(int originalArray) 1 2 3 New array that we will copy into 4 5 public int reverse(int originalArray) 1 2 3 4 5 1 Copy the first element of the original array into the last space of the new array. public int reverse(int originalArray) 1 2 3 4 5 Copy the first element of the original array into the last index of the new array. 5 1 public int reverse(int originalArray) 1 2 3 5 4 5 1 Middle Make a function call to do the next recursive step by passing in the middle array. public int reverse(int originalArray) 2 3 4 Make a new array again, copy the first and last elements accordingly. 4 2 Array passed in public int reverse(int originalArray) 2 3 4 4 2 Middle Make a new array again, this time the smaller recursive step and call reverse. Array passed in public int reverse(int originalArray) 3 We have now met our base case and can return this array to the previous function call. public int reverse(int originalArray) 2 3 4 4 2 Middle Array passed in public int reverse(int originalArray) 1 2 3 5 4 5 1 Middle public int reverse(int...
View Full Document

Ask a homework question - tutors are online