Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Which value to use as the pivot?   Consider this:  on average, for any randomly chosen element in the set (array), the value of that element is the mean of all the values.   Thus, on average, half of the values in the set are smaller than any randomly chosen value and half are thus larger.   What does this all mean?   It means that it doesn't matter which element we choose to be our pivot because on average, half of the values will be larger than our pivot and half will be smaller, which is what we want.    So, why not pick the first element?   It's statistically no different than any other elenent and its real easy to find!

Code Block

import java.util.*;
class QuicksortBasic implements QuickSort {
&nbsp;  public ArrayList<Integer> sort(ArrayList<Integer> a) {
&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;    
    if (a.isEmpty()) return new ArrayList<Integer>();
&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;    
    ArrayList<Integer> left = new ArrayList<Integer>();
&nbsp;&nbsp;&nbsp;    ArrayList<Integer> mid = new ArrayList<Integer>();
&nbsp;&nbsp;&nbsp;    ArrayList<Integer> right = new ArrayList<Integer>();
&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;    
    for (Integer i : a)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      if ( i < a.get(0) )
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
        left.add\(i); // Use element 0 as pivot
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      else if ( i > a.get(0))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
        right.add\(i);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      else 
        mid.add\(i);
&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;    
    ArrayList<Integer> left_s = sort(left);
&nbsp;&nbsp;&nbsp;    ArrayList<Integer> right_s = sort(right);
&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;    
    left_s.addAll(mid);
&nbsp;&nbsp;&nbsp; 
    left_s.addAll(right_s);
&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; 
    
    return left_s;
&nbsp;  }
}

Download the support code for this lab|^LabQuicksort.zip||\. Look at the base quicksort implementation (QuickSortBasic class), at the tests offered and at the Main program.

...