title: Recursively output a new array?
body: <p>Oddly enough I didn't find ANY information about this over the whole internet. For a homework assignment, of course.., I have to recursively add an element to its rightful place in an already-sorted array. Problem is - as arrays in java have a fixed size I cannot change my current array so I have to make a new one. That would be easy without recursion but the following code doesn't work for obvious reasons:</p>
  
  <pre><code>static int[] recursivelyInsertElement(int[] array, int index, boolean isAdded, int elem) {
  
      // Takes a sorted array with index = 0 (because.... recursion), an element
      // we'd like to insert and a boolean (default: false) to prevent us from
      // inserting the element more than once. 
  
      int[] newArray = new int[array.length + 1];
  
      if (index &gt;= array.length &amp;&amp; isAdded) {
          return newArray;
      }
  
      if (index &gt;= array.length &amp;&amp; !isAdded){
          newArray[index] = elem;
          return newArray;
      }
  
      if (array[index] &gt; elem &amp;&amp; !isAdded) {
          newArray[index] = elem;
          isAdded = true;
      }
  
      newArray[index] = array[index];
      return recursivelyInsertElement(array, index + 1, isAdded, elem);
  }
  
  
  public static void main(String[] args) {
  
      int[] array = { 1, 3, 5, 7, 9, 11, 45 };
  
      int elem = 6;
  
      int[] newArray = recursivelyInsertElement(array, 0, false, elem);
  
      for (int index = 0; index &lt; newArray.length; index++) {
          System.out.print(newArray[index] + " ");
      }
  
  }
  
  
  // Expected output: 1 3 5 6 7 9 11 45 
  // Actual output: 0 0 0 0 0 0 0 0 
  // The obvious issue here is that a new array is initialized on every step.
  // What I'd like to do is avoid this.
  </code></pre>
  
  <p>So I was wondering - how should I approach this? Make a second function which adds up the elements in a new array? Though I'm pretty sure the goal of the assignment is for my <code>recursivelyInsertElement()</code> to return the new array itself.</p>
  
  <p>P.S. I'd appreciate if you gave me just advives and tips, not whole solutions!</p>