title: Random pivot quicksort in Java
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/3358034/quick-sort-with-random-pivot-in-java">Quick Sort with random pivot in Java</a>  </p>
  </blockquote>
  
  
  
  <p>The below written code of the Quicksort uses the first element of the array as the pivot and then sorts the array. Now I want to randomly pick up the pivot instead of first one and then sort the array and I am stuck please tell me what changes I can make in the below code to get the perfect results.</p>
  
  <pre><code>import java.util.*;
  import javax.swing.JOptionPane;
  
  public class Quicksort {
  
  public static void main(String[] args) {
      String arraylength = JOptionPane.showInputDialog("Enter the length of the array.");
  
      int a = Integer.parseInt(arraylength);
      if (a == 0) {
          System.out.println("Null Length");
      } else {
          int[] list = new int[a];
  
  
          for (int i = 0; i &lt; a; i++) {
              String input = JOptionPane.showInputDialog("Input the number.");
              int c = Integer.parseInt(input);
              list[i] = c;
          }
  
          System.out.println("Before");
          for (int i = 0; i &lt; list.length; i++) {
              System.out.print(list[i] + " ");
          }
          partition(list, 0, list.length - 1);
  
  
          System.out.println("\nAfter partitionaing");
          for (int i = 0; i &lt; list.length; i++) {
              System.out.print(list[i] + " ");
          }
          quickSort(list, 0, list.length - 1);
  
          System.out.println("\nAfter Sorting");
          for (int i = 0; i &lt; list.length; i++) {
              System.out.print(list[i] + " ");
          }
      }
  }
  
  private static int partition(int[] list, int first, int last) {
      int pivot = list[first];
      int low = first + 1;
      int high = last;
  
      while (high &gt; low) {
  
          while (low &lt; high &amp;&amp; list[low] &lt; pivot) {
              low++;
          }
  
  
          while (low &lt; high &amp;&amp; list[high] &gt;= pivot) {
              high--;
          }
  
  
          if (high &gt; low) {
              int temp = list[high];
              list[high] = list[low];
              list[low] = temp;
          }
      }
      while (high &gt; first &amp;&amp; list[high] &gt;= pivot) {
          high--;
      }
  
      if (pivot &gt; list[high]) {
          list[first] = list[high];
          list[high] = pivot;
          return high;
      } else {
          return first;
      }
  
  }
  
  private static void quickSort(int[] list, int first, int last) {
      if (last &gt; first) {
          int pivotIndex = partition(list, first, last);
          quickSort(list, first, pivotIndex - 1);
          quickSort(list, pivotIndex + 1, last);
      }
  }
  }
  </code></pre>