Package utils.sort;
/**
* Quick sort, requiring that the array to be sorted must implement the comparable interface
*/
public class QuickSort implements Sortstrategy
{
private static final int CUTOFF = 3; Use fast sorting when the number of elements is greater than this value
/**
* Using the Quick sort algorithm to sort the array obj, requires that the arrays to be sorted must implement the comparable interface
*/
public void sort (comparable[] obj)
{
if (obj = null)
{
throw new NullPointerException ("The argument can not be null!");
}
QuickSort (obj, 0, obj.length-1);
}
/**
* Logarithmic group obj quick sort
* @param obj arrays to be sorted
* @param the lower bound of the left array
* @param the upper bounds of the right array
*/
private void QuickSort (comparable[] obj, int left, int right)
{
if (left + CUTOFF > right)
{
Sortstrategy ss = new Choosesort ();
Ss.sort (obj);
}
Else
{
Locate the pivot point and place it on the last side of the array
Pivot (obj, left, right);
int i = left, j = right-1;
comparable TMP = NULL;
while (true)
{
Move I, j to a position greater than/less than the pivot value
Because the first and penultimate elements of the array are less than and greater than the pivot element, the array bounds do not occur
while (Obj[++i].compareto (obj[right-1]) < 0) {}
while (Obj[--j].compareto (obj[right-1]) > 0) {}
Exchange
if (I < J)
{
TMP = Obj[i];
Obj[i] = Obj[j];
OBJ[J] = tmp;
}
Else
Break
}
Exchange Pivot value with I-point value
TMP = Obj[i];
Obj[i] = obj[right-1];
OBJ[RIGHT-1] = tmp;
A quick sort on the left and right array of pivot values
QuickSort (obj, left, i-1);
QuickSort (obj, i + 1, right);
}
}
/**
* Select the pivot element in array obj and select the method to take one of the first, middle, and last elements in the array. Place the pivot element in the penultimate position, the largest of the three in the last position of the array, the smallest in the first position
* @param obj to select an array of pivot elements
* @param the lower bound of the left array
* @param the upper bounds of the right array
*/
private void pivot (comparable[] obj, int left, int right)
{
int center = (left + right)/2;
comparable TMP = NULL;
if (Obj[left].compareto (Obj[center]) > 0)
{
TMP = Obj[left];
Obj[left] = Obj[center];
Obj[center] = tmp;
}
if (Obj[left].compareto (Obj[right]) > 0)
{
TMP = Obj[left];
Obj[left] = Obj[right];
Obj[right] = tmp;
}
if (Obj[center].compareto (Obj[right]) > 0)
{
TMP = Obj[center];
Obj[center] = Obj[right];
Obj[center] = tmp;
}
Place the pivot element in the penultimate of the array
TMP = Obj[center];
Obj[center] = obj[right-1];
OBJ[RIGHT-1] = tmp;
} }