Although the simplified partition algorithm is less efficient, it has the same order of running time:
// partition(A, s, e): partition A[s]..A[e-1] using pivot A[s] -- n = e-s
public static <T extends Comparable<T>> int partition(T[] A, int s, int e)
{
T pivot = A[s];
int low = s+1, high = e-1;
while (low <= high)
{
if ( A[high].compareTo(pivot) >= 0 )
{
high--;
}
else
{
exch(A, low, high);
low++;
}
}
exch(A, s, high); // A[s] = pivot
return high;
}
|
Note: the input size n = e-s
Synopsis of the partition algorithm:
// partition(A, s, e): partition A[s]..A[e-1] using pivot A[s]
public static <T extends Comparable<T>> int partition(T[] A, int s, int e)
{
T pivot = A[s];
int low = s+1, high = e-1;
while (low <= high)
{
doPrimitive();
Either do:
high--;
Or do:
low++;
---> Loop will run (e-1) - (s+1) times = e - 1 - s - 1 = e - s - 2
}
doPrimitive(); // 1
return high;
}
|
Running time of partition() = n - 1 ~= n (easier to remember)