<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package sort;

import java.util.Random;

public class QuickSort&lt;T extends Comparable&lt;T&gt;&gt; implements Sorter&lt;T&gt; {
   
   static Random rand = new Random();

   public void sort(T[] x) {
      sort(x, 0, x.length);
   }
   
   // sort the portion of Comparable array x between
   // lo (inclusive) and hi (exclusive) in place
   // does not touch other parts of x
   // WARNING: This version of quicksort may run into an 
   // infinite loop for arrays with duplicate elements.
   private void sort(T[] x, int lo, int hi) {
      
      // base case
      if (hi &lt;= lo + 1) return;

      // pick random pivot
      T pivot = x[lo + rand.nextInt(hi - lo)];
      
      // partition the elements about the pivot
      int i = lo;
      int j = hi - 1;
      while (true) {
         // advance indices
         while (i &lt; j &amp;&amp; x[i].compareTo(pivot) &lt; 0) i++;
         while (i &lt; j &amp;&amp; x[j].compareTo(pivot) &gt; 0) j--;
         // done?
         if (i == j) break;
         // swap
         T tmp = x[i];
         x[i] = x[j];
         x[j] = tmp;
      }
      
      // recursively sort the partition elements
      sort(x, lo, j);
      sort(x, j, hi);
   }
}

</pre></body></html>