package Utils.Sort;
/**
*快速排序,要求待排序的數組必須實(shí)現Comparable接口
*/
public class QuickSort implements SortStrategy
{
private static final int CUTOFF = 3; //當元素數大于此值時(shí)采用快速排序
/**
*利用快速排序算法對數組obj進(jìn)行排序,要求待排序的數組必須實(shí)現了Comparable接口
*/
public void sort(Comparable[] obj)
{
if (obj == null)
{
throw new NullPointerException("The argument can not be null!");
}
quickSort(obj, 0, obj.length - 1);
}
/**
*對數組obj快速排序
*@param obj 待排序的數組
*@param left 數組的下界
*@param right 數組的上界
*/
private void quickSort(Comparable[] obj, int left, int right)
{
if (left + CUTOFF > right)
{
SortStrategy ss = new ChooseSort();
ss.sort(obj);
}
else
{
//找出樞軸點(diǎn),并將它放在數組最后面的位置
pivot(obj, left, right);
int i = left, j = right - 1;
Comparable tmp = null;
while (true)
{
//將i, j分別移到大于/小于樞紐值的位置
//因為數組的第一個(gè)和倒數第二個(gè)元素分別小于和大于樞紐元,所以不會(huì )發(fā)生數組越界
while (obj[++i].compareTo(obj[right - 1]) < 0) {}
while (obj[--j].compareTo(obj[right - 1]) > 0) {}
//交換
if (i < j)
{
tmp = obj[i];
obj[i] = obj[j];
obj[j] = tmp;
}
else
break;
}
//將樞紐值與i指向的值交換
tmp = obj[i];
obj[i] = obj[right - 1];
obj[right - 1] = tmp;
//對樞紐值左側和右側數組繼續進(jìn)行快速排序
quickSort(obj, left, i - 1);
quickSort(obj, i + 1, right);
}
}
/**
*在數組obj中選取樞紐元,選取方法為取數組第一個(gè)、中間一個(gè)、最后一個(gè)元素中中間的一個(gè)。將樞紐元置于倒數第二個(gè)位置,三個(gè)中最大的放在數組最后一個(gè)位置,最小的放在第一個(gè)位置
*@param obj 要選擇樞紐元的數組
*@param left 數組的下界
*@param right 數組的上界
*/
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;
}
//將樞紐元置于數組的倒數第二個(gè)
tmp = obj[center];
obj[center] = obj[right - 1];
obj[right - 1] = tmp;
}
}
聯(lián)系客服