title: Quicksort Recursion
body: <p>So I've successfully implemented a quicksort that uses the leftmost element as the pivot every time. I've been trying to implement quicksort using the middle element and having some complicated results. I have been working off of examples that has quicksort recursively call itself without wrapping the calls in any sort of condition and, as you might imagine, it gets stuck on the first call to itself.</p>
  
  <p>The first calls to partition with the samples I've used partition the array correctly, then as it approaches the end, just swaps the two of the elements at the beginning over and over again.</p>
  
  <p>The strategy that I am attempting is to pick the middle element from the list as the pivot, stow it away at the end of the array and then proceed to swap indices. After that pass it complete, I put the pivot between the partitioned arrays. Looks good after a couple of passes, but as I mentioned, gets stuck early on and never gets to the call that should sort the second partition.</p>
  
  <p>any nudges would be greatly appreciated - I also was working in groovy, if you see anything off (and hopefully that isn't causing any issues, but I avoided duck typing for this</p>
  
  <p>the original array is </p>
  
  <p><code>[100, 305, 2, 2002, 18, 99, 211, 30, 50, 1000, 403, 4, 400, 77]</code> </p>
  
  <p>and when stack overflow is reached the array is </p>
  
  <p><code>[2, 4, 18, 30, 50, 99, 77, 100, 211, 1000, 403, 305, 400, 2002]
  </code> </p>
  
  <pre><code>class OtherQuickSort {
  
  static void sort(int[] array){
  
      quickSort(array, 0, array.length - 1)
  
  }
  
  static void quickSort(int[] array, int first, int last){
          int pivotIndex = partition(array, first, last)
  
          quickSort(array, first, pivotIndex - 1)
          quickSort(array, pivotIndex, last)
  }
  
  static int partition(int[] array, int first, int last){
      int pivotIndex = (first + last) / 2
      int pivotValue = array[pivotIndex]
  
      swapIndices(array, pivotIndex, last)
  
      int indexFromRight = last - 1
      int indexFromLeft = first
  
      while(indexFromLeft &lt;= indexFromRight){
          while(array[indexFromLeft] &lt; pivotValue){
              indexFromLeft++
          }
          while(array[indexFromRight] &gt; pivotValue){
              indexFromRight--
          }
  
          if(indexFromLeft &lt;= indexFromRight) {
              swapIndices(array, indexFromLeft, indexFromRight)
              indexFromLeft++
              indexFromRight--
          }
      }
  
      swapIndices(array, indexFromLeft, last)
  
      indexFromLeft
  }
  
  static void swapIndices(int[] array, int left, int right){
      int leftValue = array[left]
      array[left] = array[right]
      array[right] = leftValue
  }
  }
  </code></pre>