Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1. // Source code for HW 11. Demonstrates recursive method to split an array.
  2. public class SplitArray {
  3.  // Recursive method that splits array into two halves between indexes "start" and "stop"
  4.  public static void split(int[] x, int start, int stop) {
  5.   // Peek at the values of "start" and "stop" to see what's happening
  6.   System.out.println("start = " + start + ", stop = " + stop + "...");
  7.  
  8.   if (start == stop) // Base case stops recursion when no more splitting is possible
  9.    System.out.println("x[" + start + "] = " + x[start]);
  10.   else { // Split array into two halves between indexes "start" and "stop"
  11.    int mid = (stop + start) / 2; // Find middle between start and stop
  12.    split(x, start, mid); // Split the left half
  13.    split(x, mid + 1, stop); // Split the right half
  14.   }
  15.  }
  16.  
  17.  // main method to launch the recursion process
  18.  public static void main(String[] args) {
  19.   int[] data = {20, 50, 60, 80, 90}; // Should work for any size array
  20.   split(data, 0, data.length - 1);
  21.  }
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement