Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Source code for HW 11. Demonstrates recursive method to split an array.
- public class SplitArray {
- // Recursive method that splits array into two halves between indexes "start" and "stop"
- public static void split(int[] x, int start, int stop) {
- // Peek at the values of "start" and "stop" to see what's happening
- System.out.println("start = " + start + ", stop = " + stop + "...");
- if (start == stop) // Base case stops recursion when no more splitting is possible
- System.out.println("x[" + start + "] = " + x[start]);
- else { // Split array into two halves between indexes "start" and "stop"
- int mid = (stop + start) / 2; // Find middle between start and stop
- split(x, start, mid); // Split the left half
- split(x, mid + 1, stop); // Split the right half
- }
- }
- // main method to launch the recursion process
- public static void main(String[] args) {
- int[] data = {20, 50, 60, 80, 90}; // Should work for any size array
- split(data, 0, data.length - 1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement